溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

詳解java中的中斷機(jī)制

發(fā)布時間:2021-01-05 14:56:45 來源:億速云 閱讀:137 作者:Leah 欄目:開發(fā)技術(shù)

詳解java中的中斷機(jī)制?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

java 中斷api

interrupt()

interrupt()方法本質(zhì)上就是通過調(diào)用java.lang.Thread#interrupt0設(shè)置中斷flag為true,如下代碼演示了該方法的使用: 另啟一個線程中斷了當(dāng)前線程。

@Test
public void interruptSt() {
 Thread mainThread = Thread.currentThread();
 new Thread(/*將當(dāng)前線程中斷*/mainThread::interrupt).start();
 try {
 //public static native void sleep(long millis) throws InterruptedException;
 Thread.sleep(1_000);
 } catch (InterruptedException e) {
 System.out.println("main 線程被中斷了");
 }
 /*
 * 輸出: main 線程被中斷了
 */
}

interrupted()和isInterrupted()

public boolean isInterrupted() {
 // 設(shè)置this線程的中斷flag,不會重置中斷flag為true
 return isInterrupted(false);
}
public /*靜態(tài)方法*/static boolean interrupted() {
 // 設(shè)置當(dāng)前線程的中斷flag,重置中斷flag為true
 return currentThread().isInterrupted(true);
}

使用示例

@Test
public void test_Flag() {
 Thread currentThread = Thread.currentThread();
 currentThread.interrupt();
 System.out.println("當(dāng)前線程狀態(tài) =" + currentThread.isInterrupted());
 System.out.println("當(dāng)前線程狀態(tài) =" + Thread.interrupted());
 System.out.println("當(dāng)前線程狀態(tài) =" + Thread.interrupted());
 /* 輸出
 當(dāng)前線程狀態(tài) =true
 當(dāng)前線程狀態(tài) =true
 當(dāng)前線程狀態(tài) =false*/
}

三、如何響應(yīng)中斷?

調(diào)用一個可中斷的阻塞方法時需要處理受檢異常InterruptException,一般來說最容易的方式就是繼續(xù)拋出InterruptException ,讓調(diào)用方?jīng)Q定對中斷事件作出什么應(yīng)對。但是對于一些不能在方法頭直接添加異常聲明的,可以catch出后再進(jìn)行一些操作,例如使用Runnable時:

詳解java中的中斷機(jī)制

一般來說當(dāng)catch到中斷時,應(yīng)該對中斷狀態(tài)進(jìn)行還原: 調(diào)用Thread.currentThread().interrupt();,除非明確自己的操作不會丟失線程中斷的證據(jù),從而剝奪了上層棧的代碼處理中斷的機(jī)會。

總結(jié)

對目標(biāo)線程調(diào)用interrupt()方法可以請求中斷一個線程,目標(biāo)線程通過檢測isInterrupted()標(biāo)志獲取自身是否已中斷。如果目標(biāo)線程處于阻塞狀態(tài),該線程會捕獲到InterruptedException。一般來說不要catchInterruptException后不做處理(“生吞中斷”)。

看完上述內(nèi)容,你們掌握詳解java中的中斷機(jī)制的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI