執行緒的6種狀態以及轉變

不會汪汪的貓咪發表於2018-07-30

執行緒的6種狀態以及轉變:

java的執行緒一共6種狀態。具體程式碼見:

    java.lang.Thread.State
複製程式碼

1 NEW

新建狀態 Thread state for a thread which has not yet started. 執行緒還沒有呼叫start的時候

2 RUNNABLE

可執行狀態 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. 呼叫start之後,jvm啟動了這個任務,但是可能被其他資源佔用執行緒變成WAITING

3 BLOCKED

阻塞狀態 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}. 執行緒被鎖的時候,執行緒等待進去一個synchronized塊方法或者可重入鎖的時候

4 WAITING

等待狀態 Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods:

  • {@link Object#wait() Object.wait} with no timeout< li>
  • {@link #join() Thread.join} with no timeout< li>
  • {@link LockSupport#park() LockSupport.park}< li> < ul>

    A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object A thread that has called Thread.join()

執行緒呼叫object.wait thread.join LockSupport.park 的時候變成 WAITING

5 TIMED_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:

  • {@link #sleep Thread.sleep}< li>
  • {@link Object#wait(long) Object.wait} with timeout< li>
  • {@link #join(long) Thread.join} with timeout< li>
  • {@link LockSupport#parkNanos LockSupport.parkNanos}< li>
  • {@link LockSupport#parkUntil LockSupport.parkUntil}< li> < ul> sleep 或者wait,join帶時間引數等方法時

6 TERMINATED

終止狀態 Thread state for a terminated thread. The thread has completed execution. 執行緒執行完成 或者被中斷的時候變成TERMINATED TERMINATED;

_狀態流轉圖.png
狀態流轉圖

執行緒建立出來就是new的狀態。

start方法呼叫之後狀態變成runnable,可以執行,如果cpu把時間片切過來就可以執行。

runnable執行完成則變成terminated,或者中斷的時候。

runnable如果遇到有鎖的方法,在等待的時候則是阻塞blocked的狀態

如果呼叫wait或者join的方法,則變成waiting狀態,

如果呼叫帶時間引數的wait或者join,則變成time_waiting。

相關文章