Java線程的幾種狀態


java.lang.Thread.State中定義的集中Java線程的狀態:

 1 /** 
 2  * A thread state.  A thread can be in one of the following states: 
 3  * <ul> 
 4  * <li>{@link #NEW}<br> 
 5  *     A thread that has not yet started is in this state. 
 6  *     </li> 
 7  * <li>{@link #RUNNABLE}<br> 
 8  *     A thread executing in the Java virtual machine is in this state. 
 9  *     </li> 
10  * <li>{@link #BLOCKED}<br> 
11  *     A thread that is blocked waiting for a monitor lock 
12  *     is in this state. 
13  *     </li> 
14  * <li>{@link #WAITING}<br> 
15  *     A thread that is waiting indefinitely for another thread to 
16  *     perform a particular action is in this state. 
17  *     </li> 
18  * <li>{@link #TIMED_WAITING}<br> 
19  *     A thread that is waiting for another thread to perform an action 
20  *     for up to a specified waiting time is in this state. 
21  *     </li> 
22  * <li>{@link #TERMINATED}<br> 
23  *     A thread that has exited is in this state. 
24  *     </li> 
25  * </ul> 
26  * 
27  * <p> 
28  * A thread can be in only one state at a given point in time. 
29  * These states are virtual machine states which do not reflect 
30  * any operating system thread states. 
31  * 
32  * @since   1.5 
33  * @see #getState 
34  */  
35 public enum State {  
36     /** 
37      * 沒有start()的線程狀態 
38      */  
39     NEW,  
40    
41     /** 
42      * 可運行線程的線程狀態。處於可運行狀態的線程正在Java虛擬機中執行,但它可能正在等待來自操作系統(如處理器)的其他資源 
43      */  
44     RUNNABLE,  
45    
46     /** 
47      * 線程處於阻塞狀態。在進入或者重新進入synchronized代碼塊/方法時,等待monitor lock的一種狀態 
48      */  
49     BLOCKED,  
50    
51     /** 
52      * 線程處於等待狀態。,由於調用以下方法之一,線程會處於等待狀態: 
53      *    Object.wait()  沒有超時時間 
54      *    Thread.join()  沒有超時時間 
55      *    LockSupport.park() 
56      */  
57     WAITING,  
58    
59     /** 
60      * 具有指定等待時間的等待狀態。調用以下方法之一,在指定的等待時間內,使線程處於等待狀態: 
61      *   Thread.sleep 
62      *   Object#wait(long)  有超時時間 
63      *   Thread.join(long)  有超時時間 
64      *   LockSupport.parkNanos 
65      *   LockSupport.parkUntil 
66      */  
67     TIMED_WAITING,  
68    
69     /** 
70      * 終止狀態。 線程已完成執行 
71      */  
72     TERMINATED;  
73 }  

 

上述Java代碼定義的幾個狀態中其實是沒有running狀態的。

線程的runnable狀態是從虛擬機的角度來看的,表示這個線程正在運行。 但是處於Runnable狀態的線程不一定真地消耗CPU. 處於Runnable的線程只能說明該線程沒有阻塞在java的wait或者sleep方法上, 同時也沒等待在鎖上面。 但是如果該線程調用了本地方法, 而本地方法處於等待狀態, 這個時候虛擬機是不知道本地代碼中發生了什么, 此時盡管當前線程實際上也是阻塞的狀態, 但實際上顯示出來的還是runnable狀態,這種情況下是不消耗CPU的。

 

阻塞與等待的區別:

 

阻塞:當一個線程試圖獲取對象鎖(非java.util.concurrent庫中的鎖,即synchronized),而該鎖被其他線程持有,則該線程進入阻塞狀態。它的特點是使用簡單,由JVM調度器來決定喚醒自己,而不需要由另一個線程來顯式喚醒自己,不響應中斷。


等待:當一個線程等待另一個線程通知調度器一個條件時,該線程進入等待狀態。它的特點是需要等待另一個線程顯式地喚醒自己,實現靈活,語義更豐富,可響應中斷。例如調用:Object.wait()、Thread.join()以及等待Lock或Condition。

 

 

參考文章:

線程狀態


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM