對Java中interrupt、interrupted和isInterrupted的理解
今天在看到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,说明你能处理这个异常,你不希望上层调用者看到这个中断)。

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Java 8引入了Stream API,提供了一種強大且表達力豐富的處理數據集合的方式。然而,使用Stream時,一個常見問題是:如何從forEach操作中中斷或返回? 傳統循環允許提前中斷或返回,但Stream的forEach方法並不直接支持這種方式。本文將解釋原因,並探討在Stream處理系統中實現提前終止的替代方法。 延伸閱讀: Java Stream API改進 理解Stream forEach forEach方法是一個終端操作,它對Stream中的每個元素執行一個操作。它的設計意圖是處

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

膠囊是一種三維幾何圖形,由一個圓柱體和兩端各一個半球體組成。膠囊的體積可以通過將圓柱體的體積和兩端半球體的體積相加來計算。本教程將討論如何使用不同的方法在Java中計算給定膠囊的體積。 膠囊體積公式 膠囊體積的公式如下: 膠囊體積 = 圓柱體體積 兩個半球體體積 其中, r: 半球體的半徑。 h: 圓柱體的高度(不包括半球體)。 例子 1 輸入 半徑 = 5 單位 高度 = 10 單位 輸出 體積 = 1570.8 立方單位 解釋 使用公式計算體積: 體積 = π × r2 × h (4

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

Java是熱門程式語言,適合初學者和經驗豐富的開發者學習。本教學從基礎概念出發,逐步深入解說進階主題。安裝Java開發工具包後,可透過建立簡單的「Hello,World!」程式來實踐程式設計。理解程式碼後,使用命令提示字元編譯並執行程序,控制台上將輸出「Hello,World!」。學習Java開啟了程式設計之旅,隨著掌握程度加深,可創建更複雜的應用程式。
