天天看點

線程的生命周期(6 種狀态)

​​原文位址​​

線程的 6 種狀态

  • New:已建立,未啟動,已做好準備工作
  • Runnable:可運作的,調用start()方法後
  • Blocked:阻塞,進入synchronized相關方法或代碼塊,未持有鎖
  • Waiting:進入等待狀态(wait(), join(), park()),同樣喚醒方法(notify(), notifyAll(),

    unpark(), 其中join方法要等到join執行的線程執行完畢才被喚醒)

  • Timed Waiting:計時等待,需要指定時間參數,可提前被喚醒,或者等待逾時後
  • Terminated:終止,run方法執行完畢;出現未捕獲的異常意外終止

Blocked、Waiting、TimedWaiting都成為阻塞狀态

線程的生命周期(6 種狀态)

代碼示範

New / Runnable / Terminated 狀态

public class NewRunnableTerminated implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new NewRunnableTerminated());
        // 建立線程,未啟動
        System.out.println(thread.getState());
        thread.start();
        // 啟動線程,可能還未運作
        System.out.println(thread.getState());
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 已運作
        System.out.println(thread.getState());

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 運作完畢
        System.out.println(thread.getState());
    }
}      

結果展示

線程的生命周期(6 種狀态)
線程的生命周期(6 種狀态)

Blocked / Waiting / TimedWaiting 狀态

public class BlockedWaitingTimedWaiting implements Runnable{
    @Override
    public void run() {
        syn();
    }
    private synchronized void syn() {
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        Thread thread01 = new Thread(runnable);
        thread01.start();
        Thread thread02 = new Thread(runnable);
        thread02.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 線程1正在執行 Thread.sleep(1000),狀态為 TIMED_WAITING
        System.out.println(thread01.getName() + ": " + thread01.getState());
        // 線程2未拿到鎖,處于 BLOCKED 狀态
        System.out.println(thread02.getName() + ": " + thread02.getState());
        try {
            Thread.sleep(1400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // wait() 使得進入 WAITING 狀态
        System.out.println(thread01.getName() + ": " + thread01.getState());
    }
}