Java線程生命周期圖文詳細講解
線程的狀態
New
- 表示線程已創建,沒啟動的狀態
- 此時已經做瞭一些準備工作,還沒有執行run方法中代碼
Runnable
- 調用start方法之後的狀態,表示可運行狀態(不一定正在運行,因為調用start方法之後不一定立即運行)
- 如果線程拿到CPU資源,但是突然資源被搶走,這個線程依然處於Runnable
Blocked
- 線程進入到被synchronized修飾的代碼塊時,該鎖已經被其他線程拿走,此時該線程處於Blocked
- Blocked隻針對synchronized
Waiting
- 沒有設置時間參數的Object.wait方法可使線程狀態變為waiting
Timed Waiting
- 相對Waiting,有瞭時間參數
Terminated
- 執行完畢
- run方法正常執行完畢
- 或者出現瞭一個沒有被捕獲的異常終止瞭run方法
代碼演示
- 展示線程的New、Runnable、Terminated狀態
- 線程剛被new處於NEW狀態
- 調用start方法處於RUNNABLE狀態
- 程序正在執行處於RUNNABLE狀態而不是RUNNING
- 程序結束處於TERMINATED狀態
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(); // Runnable System.out.println(thread.getState()); // try { // Thread.sleep(100); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Runnable 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 < 10000; i++) { System.out.println(i); } } } /* * NEW RUNNABLE RUNNABLE * TERMINATED * */
- 演示waiting、Blocked、Timed Waiting
- 中間頻繁調用sleep方法是防止代碼執行太快,達不到應有的效果
- 線程被調用sleep,處於TIMED_WAITING
- 當一個線程執行synchronized內的代碼,另一個線程也要執行則該線程處於BLOCKED
- 線程執行wait方法,處於WAITING
public class BlockWaitingTimedWaiting implements Runnable{ public static void main(String[] args) { BlockWaitingTimedWaiting blockWaitingTimedWaiting = new BlockWaitingTimedWaiting(); Thread thread1 = new Thread(blockWaitingTimedWaiting); thread1.start(); Thread thread2 = new Thread(blockWaitingTimedWaiting); thread2.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(thread1.getState()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(thread2.getState()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } 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都被稱之為阻塞狀態
- 在阻塞狀態下,什麼時候可以繼續執行是不受控制的
到此這篇關於Java線程生命周期圖文詳細講解的文章就介紹到這瞭,更多相關Java線程生命周期內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!