Java并發編程 線程生命周期

  • 有哪6種狀態?
  • 每個狀態是什么含義
  • 狀態間的轉化圖示
  • 阻塞狀態是什么
每個狀態是什么含義
  • New
  • Runnable
  • Blocked
  • Waiting
  • Timed Waiting
  • Terminated

http://www.lxweimin.com/p/dfdc150a3e54

image.png
展示線程的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(6);
        } 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);
        }
    }
}
NEW
RUNNABLE
0
1
2
... 省略
294
295
RUNNABLE
296
297
298
... 省略
998
999
TERMINATED

Process finished with exit code 0

展示Blocked, Waiting, TimedWaiting
/**
 * 描述:     展示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();

        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread thread2 = new Thread(runnable);
        thread2.start();

        //打印出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();
        }
    }
}
TIMED_WAITING
BLOCKED
WAITING
阻塞狀態

一般習慣而言,把Blocked(被阻塞)、Waiting(等待)、Timed_waiting(即使等待)都成為阻塞狀態

  • 不僅僅是Blocked

特別感謝

悟空

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容