今天在看到Thread類別的isInterrupted方法可以取得執行緒的中斷狀態:
於是寫了個例子想驗證一下:
public class Interrupt { public static void main(String[] args) throws Exception { Thread t = new Thread(new Worker()); t.start(); Thread.sleep(200); t.interrupt(); System.out.println("Main thread stopped."); } public static class Worker implements Runnable { public void run() { System.out.println("Worker started."); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println("Worker IsInterrupted: " + Thread.currentThread().isInterrupted()); } System.out.println("Worker stopped."); } } }
內容很簡答:主執行緒main啟動了一個子執行緒Worker,然後讓worker睡500ms,而main睡200ms,之後main呼叫worker執行緒的interrupt方法去中斷worker,worker被中斷後印出中斷的狀態。以下是執行結果:
Worker started. Main thread stopped. Worker IsInterrupted: falseWorker stopped.
Worker明明已經被中斷,而isInterrupted()方法竟然回傳了false,為什麼呢?
在stackoverflow上搜尋了一圈之後,發現有網友提到:可以查看拋出InterruptedException方法的JavaDoc(或源代碼),於是我查看了Thread.sleep方法的文檔,doc中是這樣描述這個異常的:
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
這句中斷這句後面的「噹噹後中斷句點清除”。所以isInterrupted()方法應該回傳false。可是有的時候,我們需要isInterrupted這個方法回傳true,怎麼辦呢?這裡就要先說說interrupt, interrupted和isInterrupted的區別了:
interrupt方法是用於中斷線程的,調用該方法的線程的狀態將被置為"中斷"狀態。注意:線程中斷只是設定線程的中斷狀態位,不會停止線程。需要使用者自己去監視線程的狀態為並做處理。支援執行緒中斷的方法(也就是執行緒中斷後會拋出InterruptedException的方法,例如這裡的sleep,以及Object.wait等方法)就是在監視執行緒的中斷狀態,一旦執行緒的中斷狀態被置為“中斷狀態” ,就會拋出中斷異常。這個觀點可以透過這篇文章來證實:
interrupt() merely sets the thread's interruption status. Code running in the interrupted thread can later poll the interrupted status to see if it has been requested tos top what do看interrupted方法的實作:
public static boolean interrupted() { return currentThread().isInterrupted(true); }
和isInterrupted的實作:
public boolean isInterrupted() { return isInterrupted(false); }
這兩個方法一個是static的,一個不是,但實際上都是在呼叫同一個方法,只是interrupted方法傳入的參數為true,而inInterrupted傳入的參數為false。那麼這個參數到底是什麼意思呢?來看下這個isInterrupted(boolean)方法的實作:
/** * Tests if some Thread has been interrupted. The interrupted state * is reset or not based on the value of ClearInterrupted that is * passed. */private native boolean isInterrupted(boolean ClearInterrupted);
這是一個native方法,看不到原始碼沒有關係,參數名字ClearInterrupted已經清楚的表達了該參數的作用----是否清除中斷狀態。方法的註解也清楚的表達了「中斷狀態將會根據傳入的ClearInterrupted參數值來決定是否重置」。所以,靜態方法interrupted將會清除中斷狀態(傳入的參數ClearInterrupted為true),而實例方法isInterrupted則不會(傳入的參數ClearInterrupted為false)。
回到剛剛的問題:很明顯,如果要isInterrupted這個方法回傳true,透過在呼叫isInterrupted方法之前再次呼叫interrupt()方法來恢復這個中斷的狀態即可:
public class Interrupt { public static void main(String[] args) throws Exception { Thread t = new Thread(new Worker()); t.start(); Thread.sleep(200); t.interrupt(); System.out.println("Main thread stopped."); } public static class Worker implements Runnable { public void run() { System.out.println("Worker started."); try { Thread.sleep(500); } catch (InterruptedException e) { Thread curr = Thread.currentThread(); //再次调用interrupt方法中断自己,将中断状态设置为“中断” curr.interrupt(); System.out.println("Worker IsInterrupted: " + curr.isInterrupted()); System.out.println("Worker IsInterrupted: " + curr.isInterrupted()); System.out.println("Static Call: " + Thread.interrupted());//clear status System.out.println("---------After Interrupt Status Cleared----------"); System.out.println("Static Call: " + Thread.interrupted()); System.out.println("Worker IsInterrupted: " + curr.isInterrupted()); System.out.println("Worker IsInterrupted: " + curr.isInterrupted()); } System.out.println("Worker stopped."); } } }執行結果:
Worker started. Main thread stopped. Worker IsInterrupted: true Worker IsInterrupted: true Static Call: true ---------After Interrupt Status Cleared---------- Static Call: false Worker IsInterrupted: false Worker IsInterrupted: false Worker stopped.
public class TaskRunner implements Runnable { private BlockingQueue<Task> queue; public TaskRunner(BlockingQueue<Task> queue) { this.queue = queue; } public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } }
執行結果:
rrreee執行結果:rrreee
🎜執行結果:🎜🎜🎜rrreee rrreee🎜🎜🎜🎜🎜從執行結果也可以看到,前兩次調用isInterrupted方法都回傳true,說明isInterrupted方法不會改變執行緒的中斷狀態,而接下來調用靜態的interrupted()方法,第一次返回了true,表示執行緒被中斷,第二次則回傳了false,因為第一次呼叫的時候已經清除了中斷狀態。最後兩次呼叫isInterrupted()方法就肯定回傳false了。 🎜🎜那麼,在什麼場景下,我們需要在catch區塊裡面中斷執行緒(重置中斷狀態)呢? 🎜🎜答案是:如果不能拋出InterruptedException(就像這裡的Thread.sleep語句放在了Runnable的run方法中,這個方法不允許拋出任何受檢查的異常),但又想告訴上層呼叫者這裡發生了中斷的時候,就只能在catch裡面重置中斷狀態了。 🎜🎜If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can lrup of the interrupt and resruped interrupced 片 interruped tocx interrupt interrupt] interrupt interruped interruped topruped 問題 interruped tos interrupt interrupt interrupt interrupt 片段 topruped 1很多。 t( ) to "reinterrupt" the current thread, as shown in Listing 3.🎜🎜 Listing 3: Restoring the interrupted status after catching InterruptedException🎜public class TaskRunner implements Runnable { private BlockingQueue<Task> queue; public TaskRunner(BlockingQueue<Task> queue) { this.queue = queue; } public void run() { try { while (true) { Task task = queue.take(10, TimeUnit.SECONDS); task.execute(); } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); } } }
那么问题来了:为什么要在抛出InterruptedException的时候清除掉中断状态呢?
这个问题没有找到官方的解释,估计只有Java设计者们才能回答了。但这里的解释似乎比较合理:一个中断应该只被处理一次(你catch了这个InterruptedException,说明你能处理这个异常,你不希望上层调用者看到这个中断)。