執行緒的6種狀態
阿新 • • 發佈:2018-12-22
以下是java原始碼
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; }
一、NEW(新建狀態)
尚未啟動的執行緒的執行緒狀態。
二、RUNNABLE(可執行狀態)
可執行執行緒的執行緒狀態。runnablestate中的一個執行緒正在Java虛擬機器中執行,但它可能等待作業系統(如處理器)的其他資源。
三、BLOCKED(阻塞狀態)
執行緒狀態為等待監視器鎖的執行緒阻塞。處於阻塞狀態的執行緒正在等待監視器鎖輸入同步塊/方法或呼叫Object.wait後重新輸入同步塊/方法。
四、WAITING(無時間等待狀態)
等待執行緒的執行緒狀態。由於呼叫以下方法之一,執行緒處於等待狀態:
處於等待狀態的執行緒正在等待另一個執行緒對一個特定動作執行操作。例如,在物件上呼叫object. wait()的執行緒正在等待另一個執行緒在該物件上呼叫object. notify()或object. notifyall()。呼叫thread .join()的執行緒正在等待指定的執行緒終止。
六、TERMINATED(終止狀態)
退出的執行緒處於這種狀態。
總結:
執行緒在給定的時間點上只能處於一種狀態。這些狀態是不反映任何作業系統執行緒狀態的虛擬機器狀態。