前言:對於Java線程狀態方面的知識點,筆者總感覺朦朦朧朧,趁着最近整理資料,將Java線程狀態方面的知識點總結歸納,以便加深記憶。
1.Java線程狀態值
在Thread類源碼中通過枚舉為線程定義了6種狀態值。
1 public enum State { 2 /** 3 * Thread state for a thread which has not yet started. 4 */ 5 NEW, 6 7 /** 8 * Thread state for a runnable thread. A thread in the runnable 9 * state is executing in the Java virtual machine but it may 10 * be waiting for other resources from the operating system 11 * such as processor. 12 */ 13 RUNNABLE, 14 15 /** 16 * Thread state for a thread blocked waiting for a monitor lock. 17 * A thread in the blocked state is waiting for a monitor lock 18 * to enter a synchronized block/method or 19 * reenter a synchronized block/method after calling 20 * {@link Object#wait() Object.wait}. 21 */ 22 BLOCKED, 23 24 /** 25 * Thread state for a waiting thread. 26 * A thread is in the waiting state due to calling one of the 27 * following methods: 28 * <ul> 29 * <li>{@link Object#wait() Object.wait} with no timeout</li> 30 * <li>{@link #join() Thread.join} with no timeout</li> 31 * <li>{@link LockSupport#park() LockSupport.park}</li> 32 * </ul> 33 * 34 * <p>A thread in the waiting state is waiting for another thread to 35 * perform a particular action. 36 * 37 * For example, a thread that has called <tt>Object.wait()</tt> 38 * on an object is waiting for another thread to call 39 * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on 40 * that object. A thread that has called <tt>Thread.join()</tt> 41 * is waiting for a specified thread to terminate. 42 */ 43 WAITING, 44 45 /** 46 * Thread state for a waiting thread with a specified waiting time. 47 * A thread is in the timed waiting state due to calling one of 48 * the following methods with a specified positive waiting time: 49 * <ul> 50 * <li>{@link #sleep Thread.sleep}</li> 51 * <li>{@link Object#wait(long) Object.wait} with timeout</li> 52 * <li>{@link #join(long) Thread.join} with timeout</li> 53 * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> 54 * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> 55 * </ul> 56 */ 57 TIMED_WAITING, 58 59 /** 60 * Thread state for a terminated thread. 61 * The thread has completed execution. 62 */ 63 TERMINATED; 64 }
NEW ---- 創建了線程對象但尚未調用start()方法時的狀態。
RUNNABLE ---- 線程對象調用start()方法后,線程處於可運行狀態,此時線程等待獲取CPU執行權。
BLOCKED ---- 線程等待獲取鎖時的狀態。
WAITING ---- 線程處於等待狀態,處於該狀態標識當前線程需要等待其他線程做出一些特定的操作喚醒自己。
TIME_WAITING ---- 超時等待狀態,與WAITING不同,在等待指定的時間后會自行返回。
TERMINATED ---- 終止狀態,表示當前線程已執行完畢。
2.線程狀態轉換
- 看圖理解,下圖對線程狀態轉換描述得非常清楚。
- 繼續看圖,將上下兩張圖片結合起來,理解就非常容易了。
- 只要充分理解上述兩張圖片,筆者相信就可以搞懂Java線程狀態的轉換關系了,如果你還有點懵懂,那么請看下圖:
注:以上三張圖片均來自於參考文章,對於最后一張圖片有個小問題:t2.join()方法會釋放鎖。
總結
通過以上三張圖片的描述,對Java線程狀態轉換的核心要點總結如下:
其實通過上面三張圖片已經能很好的說明問題了,過多的總結反倒顯得蒼白無力。主要注意WAITING和BLOCKED狀態:這兩個狀態下的線程都未運行,BLOCKED狀態下,線程正等待鎖;WAITING狀態下,線程正等待被喚醒,喚醒后可能進入BLOCKED狀態,繼續等待鎖,或者進入RUNNABLE狀態,重新獲取CPU時間片,繼而等待獲取鎖。
參考:
https://my.oschina.net/mingdongcheng/blog/139263
https://github.com/c-rainstorm/blog/blob/master/java/談談Java線程狀態轉換.md
by Shawn Chen,2019.02.17,下午。