標籤:而在 start key aqs syn ssi 處理器 fancybox 選擇
http://blog.jrwang.me/2016/java-thread-states/發表於 2016-07-23
在 Java 多線程編程中,sleep(), interrupt(), wait(), notify() 等方法是非常基本也很常用的方法。這些方法會改變運行中的 Java 線程的狀態,正確地認識這些方法是掌握 Java 並發編程的基本要求。
Java 線程的狀態
先來談一談 Java 中線程的狀態。在 Java 中,線程的狀態和底層作業系統中線程的狀態並不是一一對應的關係,我們所能見到的是 JVM 虛擬機器層面暴露的狀態。
Java 中線程的狀態在 Thread 的內部枚舉類 Thread.State 中定義,有 NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED 這六類狀態。
在 Java 的官方文檔中寫道:“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 狀態的線程在 JVM 虛擬機器正在 JAVA 虛擬機器中執行,但它可能正在等待來自於作業系統的其它資源,比如處理器。實際上,如果一個線程在等待阻塞I/O的操作時,它的狀態也是 RUNNABLE 的。
如果一個線程在擷取對象鎖的過程中阻塞了(synchronized關鍵字),它就處於 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 Object.wait.
而如果是由於調用了下面這三類方法,則線程會處於 WAITING 狀態,需要等待其他的線程將其喚醒:
Object.wait with no timeout
Thread.join with no timeout
LockSupport.park
如果是通過 Lock.lock() 方法等待擷取鎖時,也會處於 WAITING 狀態。因為 Lock 介面的實現基於 AQS 實現的,而 AQS 中的阻塞操作都是基於 LockSupport 工具類實現的。
TIMED_WAITING 狀態和 WAITING 狀態類似,只不過等待的是逾時事件的發生,下面幾種方法會使得線程進入該狀態:
Thread.sleep
Object.wait with timeout
Thread.join with timeout
LockSupport.parkNanos
LockSupport.parkUntil
同樣,帶有逾時的 Lock.tryLock(long time, TimeUnit unit) 方法在等待擷取鎖時也會進入該狀態。
通常,在作業系統這一層面,線程存在五類狀態,狀態的轉換關係可以參考下面的這張圖。
可以看到,JVM 中所說的線程狀態和 OS 層面的線程狀態是不太一樣的。JVM 中 RUNNABLE 其實是包含了中的 RUNNING, READY, 和部分 WAITING 狀態的;而 JVM 中 WAITING, TIMED_WAITING 和 BLOCKED 其實又是對中 WAITING 剩餘情形的一個更細緻的劃分。
sleep vs wait
sleep(long) 和 wait() 方法都能讓線程暫停執行,並讓出當前的處理器資源。但是,這兩個方法存在一些本質的區別。
sleep(long) 方法是在 Thread 類中定義的靜態方法,會使得線程睡眠(即暫時停止運行)一段指定的時間,進入 TIMED_WAITING 狀態;當逾時後重新進入 RUNNABLE 狀態。sleep()方法會保留當前線程的運行狀態,線程所持有的鎖資源並不會釋放。
wait() 方法是在 Object 上定義的方法,任何一個類都從 Object 類中繼承了該方法。調用該方法(obj.wait())的前提是當前線程擷取了該對象(obj)的鎖。調用該方法後,線程會進入 WAITING 狀態,同時會釋放持有的對象上的鎖,JVM 會將該線程置於對象的等待隊列中。wait()方法需要通過 obj.notify() 或 obj.notifyAll() 來進行喚醒,notify()和notifyAll()會將對象的等待隊列中的一個或全部線程移入對象的同步隊列中來競爭對象的鎖,當擷取鎖之後便從 wait() 方法中返回了。簡單地說, wait() 方法會釋放線程持有的鎖,並等待 notify() 或 notifyAll() 喚醒,從 wait() 方法返回表明線程又重新擷取了對象鎖。
wait(long) 是 wait() 的一個重載版本,效果基本一致,只是 wait(long) 進入 TIMED_WAITING 狀態,逾時也可以被喚醒。
interrupt
很多人看到 interrupt() 方法,認為“中斷”線程不就是讓線程停止嘛。實際上, interrupt() 方法實現的根本就不是這個效果, interrupt()方法更像是發出一個訊號,這個訊號會改變線程的一個標識位屬性(中斷標識),對於這個訊號如何進行相應則是無法確定的(可以有不同的處理邏輯)。很多時候調用 interrupt() 方法非但不是為了停止線程,反而是為了讓線程繼續運行下去。
在 Java 的文檔中對 interrupt() 的效果列了四種情形:
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an InterruptibleChannel then the channel will be closed, the thread’s interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread’s interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector’s wakeup method were invoked.
If none of the previous conditions hold then this thread’s interrupt status will be set.
前三種情形其實是描述了如果線程處於等待狀態或是阻塞在某一種資源上,那麼 interrupt()方法會使得線程跳出這種狀態繼續執行下去。第四種情形則描述了如果線程正在正常執行,那麼 interrupt() 的效果則是設定了線程的中斷狀態,至於怎麼處理這種狀態,可以選擇忽略也可以按需處理。
可以通過 isInterrupted() 方法來測試當前線程的中斷標識的狀態;靜態方法 Thread.interrupted() 可以判斷當前線程是否處於中斷狀態,同時也會清除當前的中斷狀態。通常使用 Thread.interrupted() 來複位中斷標識。在第一種情形的表示中我們可以看到,在拋出 InterruptedException 前會清除中斷標識,因而在異常處理中調用 isInterrupted() 會返回 false。
如果線程調用 sleep(long) 方法睡眠了非常長的一段時間,現在想要將它喚醒,就可以調用 interrupt() 方法。注意是在 wait(), sleep(), join() 方法聲明中的異常,可見不是調用 interrupt() 拋出異常,而是在 wait(), sleep(), join() 處於等待的過程中,調用 interrupt() 方法會使其從等待狀態中返回,並收到 InterruptedException 異常,進而將控制邏輯交給異常處理語句。
在 wait() 方法中等待的線程被中斷時,和使用 notify() 喚醒一樣,必須要重新獲得對象的鎖才能從方法中返回,而不是立即就能返回並進入異常處理。下面這個例子簡單地驗證一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
public class InterruptDemo { public static void main(String[] args) throws InterruptedException{ WN wn = new WN();
Thread t1 = new Thread(new Runnable() { @Override public void run() { wn.m1(); } }); t1.setName("thread 1");
Thread t2 = new Thread(new Runnable() { @Override public void run() { wn.m2(); } }); t2.setName("thread 2");
t1.start(); t2.start();
Thread.sleep(1000L); System.out.println("call interrupt @" + System.currentTimeMillis()); t1.interrupt(); }
static class WN { private Object o = new Object();
public void m1() { synchronized (o) { System.out.println(Thread.currentThread().getName() + " get lock @" + System.currentTimeMillis()); try { o.wait(); System.out.println("return from wait() @" + System.currentTimeMillis()); } catch (InterruptedException e) { System.out.println("interrupted during obj.wait() @" + System .currentTimeMillis()); } } }
public void m2() { synchronized (o) { System.out.println(Thread.currentThread().getName() + " get lock @" + System.currentTimeMillis()); try { Thread.sleep(10000L); System.out.println(Thread.currentThread().getName() + " release lock @" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }
} }
|
輸出的結果:
1 2 3 4 5
|
thread 1 get lock @1471189560880 thread 2 get lock @1471189560880 call interrupt @1471189561880 thread 2 release lock @1471189570881 interrupted during obj.wait() @1471189570881
|
可以看到,只有線上程2釋放了鎖之後(只有線程2釋放了線程1才能重新擷取),才能從wait()方法中返回。
yield
yield() 方法是 Thread 類的靜態方法,也用於出讓當前線程佔用的CPU資源。和 sleep(long) 方法不同的是, sleep(long)會使得線程進入 WAITING 狀態並且至少會等待逾時時間到達後才會再次執行;而 yield() 方法則是從 RUNNING 進入 READY 狀態(這裡指的是作業系統層面,在 JVM 暴露出來的都是 RUNNABLE 狀態),因而極有可能馬上又被調度選中繼續運行。
A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
從文檔中的表述來看,yield() 方法相比於 sleep(long) 方法更依賴與系統的調度。該方法並不經常用到。
-EOF-
談談 Java 線程狀態相關的幾個方法