java線程的生命週期及創建方式

線程,一直都是非常基礎且重要的知識點,因爲,在多線程下,什麼都可能發生。

線程生命週期

線程是一個動態執行到過程,從出生,到死亡。

  1. New(創建,初始化狀態)
  2. Runnable(可運行/運行狀態)
  3. Blocked(阻塞狀態)
  4. Waiting(無時間限制的等待狀態)
  5. Timed_Waiting(有時間限制的等待狀態)
  6. Terminated(終止狀態)

線程創建

1、繼承Thread類

public class MyThread extends Thread {
	public MyThread() {
		
	}
	public void run() {
		for(int i=0;i<10;i++) {
			System.out.println(Thread.currentThread()+":"+i);
		}
	}
	public static void main(String[] args) {
		MyThread thread1=new MyThread();
		MyThread thread2=new MyThread();
		MyThread thread3=new MyThread();
		thread1.start();
		thread2.start();
		thread3.start();
	}
}

2.覆寫Runnable()接口

public class MyThread implements Runnable{
	public static int count=20;
	public void run() {
		while(count>0) {
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"-當前剩餘票數:"+count--);
		}
	}
	public static void main(String[] args) {
		MyThread Thread1=new MyThread();
		Thread thread1=new Thread(Thread1,"線程1");
		Thread thread2=new Thread(Thread1,"線程2");
		Thread thread3=new Thread(Thread1,"線程3");
		thread1.start();
		thread2.start();
		thread3.start();
	}
}

3,使用線程池

FixThreadPool(int n); 固定大小的線程池

SingleThreadPoolExecutor :單線程池

CashedThreadPool(); 緩存線程池

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章