1. 程式人生 > >多執行緒——執行緒的幾種狀態 (Java API版)

多執行緒——執行緒的幾種狀態 (Java API版)

以前學習作業系統這門課程的時候,對執行緒狀態的學習是比較粗略的,僅限於表面的瞭解,在後續學習和使用的過程中,
我發現自己之前的認知與Java api中定義的執行緒狀態是有出入的,在使用過程中也會有很多誤解,
所以按照java.lang.Thread.State中的詳細定義和說明,進行了如下整理,作為自我總結和學習。

根據Java api,Java中執行緒一共有如下6種狀態,即NEW、RUNNABLE、BLOCKED、WAITING、TIME_WAITING、TERMINATED

1. NEW

NEW: 新建狀態,指已經建立了執行緒物件,但是該執行緒尚未啟動,即還沒有呼叫start()

方法。根據Java api,定義如下:

Thread state for a thread which has not yet started

2. RUNNABLE

RUNNABLE: 按照字面翻譯是“可執行的”, 但是根據Java api中的定義:

A thread in the runnable state is executing in the jvm but it may be waiting for other resources from the operating system such as processor

因此,說該狀態是“執行中”更恰當,此外在該狀態下執行緒有可能會因對作業系統的資源請求(例如IO請求)而處於等待中,
總之,該狀態下發生的等待是與系統資源

有關的,與鎖無關。

3. BLOCKED

BLOCKED:阻塞狀態,根據Java api中的定義:

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 Object.wait()

這個狀態發生在涉及到多個執行緒同步的問題中,執行緒等待獲取從而進入臨界區,因此,值得注意的是,
該狀態的等待與上述runnable狀態下中可能出現的等待,它們的誘發原因是不同的。
總之,該狀態下執行緒在等待進入臨界區

4. WAITING

WAITING:等待狀態,根據Java api,該狀態的誘發原因如下:

A thread is in the waiting state due to calling one of the following methods:
Object.wait with no timeout
Thread.join with no timeout
LockSupport.park

因此,該狀態一般出現在呼叫wait()、join()和park()的情況。
根據Java api,對改狀態的定義如下:

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() is waiting for a specified thread to terminate

這個狀態是指執行緒在是獲取了鎖之後,由於上述方法被呼叫,從而導致執行緒失去對鎖的所有權,進入等待佇列,等待其他執行緒執行相應的動作。
參看wait()方法和join方法的介紹,未完待續~

5. TIMED_WAITING

TIME_WAITING:有限時間的等待狀態,根據Java api的定義,該狀態的誘發原因如下:

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:
Thread.sleep
Object.wait with timeout
Thread.join with timeout
LockSupport.parkNanos
LockSupport.parkUntil

因此,該狀態一般出現在呼叫
sleep(long millis)、wait(long timeout)、join(long millis)、parkNanos(long nanos)和 parkUntil(long deadline)的情況。

6. TERMINATED

TERMINATED:終止狀態/死亡狀態,指執行緒執行完畢,該執行緒的run()方法已執行完畢。根據Java api,定義如下:

The thread has completed execution.

其實,根據API中的英文定義,很容易體會和理解執行緒的各個狀態是什麼樣子的,反而硬是要翻譯過來的話,卻無法恰當描述出來。

根據上述內容畫的流程圖如下:

這裡寫圖片描述

這裡寫圖片描述