聊聊Java 中的線程中斷
Java如何實現(xiàn)線程中斷?
通過調(diào)用Thread類的實例方法interrupt
。如下:
Thread thread = new Thread(){ @Override public void run() { if(isInterrupted()){ System.out.println("interrupt"); } } }; thread.start(); thread.interrupt();
線程中斷后線程會立即停止執(zhí)行嗎?
NO。 而如果線程未阻塞,或未關心中斷狀態(tài),則線程會正常執(zhí)行,不會被打斷。
Thread.interrupt()的官方解釋是這樣的:
If this thread is blocked in an invocation of the
Object#wait() wait(), { Object#wait(long) wait(long)}, or { Object#wait(long, int) 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}.
也就是:處于阻塞的線程,即在執(zhí)行Object對象的wait()、wait(long)、wait(long, int),或者線程類的join()、join(long)、join(long, int)、sleep(long)、sleep(long,int)方法后線程的狀態(tài),當線程調(diào)用interrupt()方法后,這些方法將拋出InterruptedException異常,并清空線程的中斷狀態(tài)。
比如下面的例子會中斷兩次,第一次sleep方法收到中斷信號后拋出了InterruptedException,捕獲異常后中斷狀態(tài)清空,然后繼續(xù)執(zhí)行下一次:
public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(){ @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("interrupt"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); thread.interrupt(); Thread.sleep(5000); thread.interrupt(); }
而下面這個例子則會一直執(zhí)行,不會被打斷:
public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(){ @Override public void run() { while (true) System.out.println("interrupt"); } }; thread.start(); thread.interrupt(); }
interrupted與isInterrupted方法啥區(qū)別?
- Thread類的靜態(tài)方法interrupted:測試當前線程是否已經(jīng)中斷。如果線程處于中斷狀態(tài)返回true,否則返回false。同時該方法將清除的線程的中斷狀態(tài)。即:如果連續(xù)兩次調(diào)用該方法,則第二次調(diào)用將返回false。該方法可用于清除線程中斷狀態(tài)使用。
- Thread類的實例方法isInterrupted:測試線程是否已經(jīng)中斷。線程的中斷狀態(tài)不受該方法的影響。
Thread類并沒有提供單獨清除中斷狀態(tài)的方法,所以有兩種方式來達到此目的:
- 對于sleep等阻塞方法,catch InterruptedException異常;
- 調(diào)用Thread類的靜態(tài)方法interrupted
線程中斷有哪些實際應用?
線程中斷的幾個實際應用場景:
- 在處理Web請求時,可能將請求分配到多個線程去處理,實現(xiàn)請求執(zhí)行的超時機制;
- 實現(xiàn)線程池時,關閉線程池中的線程任務。
以上就是聊聊Java 中的線程中斷的詳細內(nèi)容,更多關于Java 線程中斷的資料請關注腳本之家其它相關文章!
相關文章
Spring加載配置和讀取多個Properties文件的講解
今天小編就為大家分享一篇關于Spring加載配置和讀取多個Properties文件的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03springboot實戰(zhàn)權限管理功能圖文步驟附含源碼
這篇文章主要為大家介紹了springboot實戰(zhàn)權限管理功能圖文步驟及示例源碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-062024版本IDEA創(chuàng)建Servlet模板的圖文教程
新版IDEA?2024.1.4中,用戶需要自行創(chuàng)建Servlet模板以解決Web項目無法通過右鍵創(chuàng)建Servlet的問題,本文詳細介紹了添加ServletAnnotatedClass.java模板的步驟,幫助用戶快速配置并使用新的Servlet模板,需要的朋友可以參考下2024-10-10詳解Java中Checked Exception與Runtime Exception 的區(qū)別
這篇文章主要介紹了詳解Java中Checked Exception與Runtime Exception 的區(qū)別的相關資料,這里提供實例幫助大家學習理解這部分內(nèi)容,需要的朋友可以參考下2017-08-08