線程的6個狀態(生命週期)

線程的一生

有哪六種狀態?

  • New
  • Runnable
  • Blocked
  • Waiting
  • Timed Waiting
  • Terminated

每個狀態是什麼含義?

新建New、可運行Runnable、已終止Terminated
代碼演示

/**
 * 展示線程的NEW、RUNNABLE、Terminated狀態。即使是正在運行,也是Runnable狀態,而不是Running。
 */
public class NewRunnableTerminated implements Runnable {

    public static void main(String[] args) {

        Thread thread = new Thread(new NewRunnableTerminated());
        //打印出NEW的狀態
        System.out.println(thread.getState());
        thread.start();
        System.out.println(thread.getState());
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出RUNNABLE的狀態,即使是正在運行,也是RUNNABLE,而不是RUNNING
        System.out.println(thread.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出TERMINATED狀態
        System.out.println(thread.getState());
    }

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

被阻塞Blocked、等待Waiting、計時等待Timed Waiting
代碼演示

/**
 * 展示Blocked, Waiting, TimedWaiting
 */
public class BlockedWaitingTimedWaiting implements Runnable {

    public static void main(String[] args) {
        BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread thread2 = new Thread(runnable);
        thread2.start();
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出Timed_Waiting狀態,因爲正在執行Thread.sleep(1000);
        System.out.println(thread1.getState());
        //打印出BLOCKED狀態,因爲thread2想拿得到sync()的鎖卻拿不到
        System.out.println(thread2.getState());
        try {
            Thread.sleep(1300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印出WAITING狀態,因爲執行了wait()
        System.out.println(thread1.getState());
    }

    @Override
    public void run() {
        syn();
    }

    private synchronized void syn() {
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

狀態間的轉化圖示

狀態間的轉換圖示

阻塞狀態是什麼?

  • 一般來說,把Blocked(被阻塞)、Waiting(等待)、Timed_waiting(計時等待)都稱爲阻塞狀態
  • 不僅僅是Blocked

面試問題

1.線程有哪幾種狀態?生命週期是什麼?

先講上面狀態間的轉化圖示圓圈中的狀態名,再講講轉換路徑(例如New只能跳轉到Runnable),最後講講轉移條件。

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