看到網上關於線程狀態轉移的博客,好多都沒說明白。查了不少資料,彙總一篇,但願經過這一篇,能把這些狀態轉移解釋明白,若是有什麼沒考慮到的,但願指正html
轉載註明出處原文地址:http://www.javashuo.com/article/p-qonfhpvx-dk.htmlide
Thread t1 = new Thread( new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("hello : " + i); } } } ); // t1執行start()以後,處於就緒態,操做系統此時能夠分配時間片給該線程,讓該線程執行run方法體中的內容 t1.start();
public static void main(String[] args) { // 線程1 Thread t1 = new Thread(() -> { for (int i = 0; i < 10; i++) { System.out.println("t1 : running"); } }); t1.start(); // 線程2 Thread t2 = new Thread(() -> { for (int i = 0; i < 10; i++) { System.out.println("t2 : running"); } }); t2.start(); }
public static void main(String[] args) { // 線程1 Thread t1 = new Thread(() -> { Thread.yield(); for (int i = 0; i < 10; i++) { System.out.println("t1 : running " + i); } }); t1.start(); // 線程2 Thread t2 = new Thread(() -> { for (int i = 0; i < 10; i++) { System.out.println("t2 : running " + i); } }); t2.start(); }
public static void main(String[] args) { Thread t1 = new Thread(() -> { for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("hello : " + i); } } ); // t1執行start()以後,處於就緒態,操做系統此時能夠分配時間片給該線程 t1.start(); }
public class TestThread { static Thread t1; static Thread t2; public static void main(String[] args) { // 線程1 t1 = new Thread(() -> { for (int i = 0; i < 100; i++) { if(i == 50) { try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("t1 : running " + i); } }); t1.start(); // 線程2 t2 = new Thread(() -> { for (int i = 0; i < 100; i++) { System.out.println("t2 : running " + i); } }); t2.start(); } }
這個很好理解,好比你就執行一個main函數的主線程,等待輸入時,該線程是不會結束的,就是處於阻塞狀態。函數
這裏牽扯到對象鎖的概念操作系統
public static void main(String[] args) { Object o = new Object(); // 線程1 Thread t1 = new Thread(() -> { synchronized (o) { for (int i = 0; i < 10; i++) { try { if(i == 5) { // 當i=5的時候,讓出對象鎖,t1進入等待隊列 // 若是沒人通知,t1一直等待,程序不會結束 o.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("t1 : running " + i); } } }); t1.start(); // 線程2 Thread t2 = new Thread(() -> { synchronized (o) { for (int i = 0; i < 10; i++) { System.out.println("t2 : running " + i); } // 這裏t2獲得鎖,執行完線程方法以後必定要通知t1中止等待。 // 否則t1結束不了,處在一直等待通知的狀態 o.notify(); } }); t2.start(); }
死亡態不可逆,一旦線程進入死亡態,就再也回不到其餘狀態線程