Java線程狀態
阿新 • • 發佈:2019-04-22
min virtual 通過 clas 顯示 lang park posit 進入
Java線程的狀態分為NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED,通過枚舉類java.lang.Thread.State定義。
public enum State { /** * Thread state for a thread which has not yet started. */ NEW, /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor.*/ RUNNABLE, /** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ BLOCKED, /** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called <tt>Object.wait()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on * that object. A thread that has called <tt>Thread.join()</tt> * is waiting for a specified thread to terminate. */ WAITING, /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }
1.NEW表示線程創建後尚未啟動
2.RUNNABLE表示線程處於可運行狀態,有可能正在被CPU執行或者等待CPU調度
3.BLOCKED表示阻塞狀態,表明線程正在等待監視器鎖。當線程正在等待監視器鎖進入synchronized塊/方法時,或調用Object.wait方法後重新進入synchronized塊/方法時。
4.WAITING表示無限期等待狀態。處於這種狀態的線程不會被分配CPU執行時間,它們要等待顯示的被其它線程喚醒。
以下方法會讓線程陷入無限期等待狀態:
(1)沒有設置timeout參數的Object.wait()
(2)沒有設置timeout參數的Thread.join()
(3)LockSupport.park()
5.TIMED_WAITING表示超時等待狀態。處於這種狀態的線程也不會被分配CPU執行時間,不過無需等待被其它線程顯示的喚醒,在一定時間之後它們會由系統自動的喚醒。
以下方法會讓線程進入TIMED_WAITING超時等待狀態:
(1)Thread.sleep()方法
(2)設置了timeout參數的Object.wait()方法
(3)設置了timeout參數的Thread.join()方法
(4)LockSupport.parkNanos()方法
(5)LockSupport.parkUntil()方法
6.TERMINATED表示結束狀態,表示線程已經結束執行
Java線程狀態