小編給大家分享一下java如何捕獲InterruptedException錯誤,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

你所需要的網(wǎng)站建設(shè)服務(wù),我們均能行業(yè)靠前的水平為你提供.標(biāo)準(zhǔn)是產(chǎn)品質(zhì)量的保證,主要從事成都網(wǎng)站建設(shè)、成都網(wǎng)站制作、企業(yè)網(wǎng)站建設(shè)、移動網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計、成都品牌網(wǎng)站建設(shè)、網(wǎng)頁制作、做網(wǎng)站、建網(wǎng)站。創(chuàng)新互聯(lián)建站擁有實力堅強的技術(shù)研發(fā)團隊及素養(yǎng)的視覺設(shè)計專才。
捕獲InterruptedException錯誤
請檢查下面的代碼片段:
public class Task implements Runnable {
private final BlockingQueue queue = ...;
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
String result = getOrDefault(() -> queue.poll(1L, TimeUnit.MINUTES), "default");
//do smth with the result
}
}
T getOrDefault(Callable supplier, T defaultValue) {
try {
return supplier.call();
}
catch (Exception e) {
logger.error("Got exception while retrieving value.", e);
return defaultValue;
}
}
}代碼的問題是,在等待隊列中的新元素時,是不可能終止線程的,因為中斷的標(biāo)志永遠不會被恢復(fù):
1.運行代碼的線程被中斷。
2.BlockingQueue # poll()方法拋出InterruptedException異常,并清除了中斷的標(biāo)志。
3.while中的循環(huán)條件 (!Thread.currentThread().isInterrupted())的判斷是true,因為標(biāo)記已被清除。
為了防止這種行為,當(dāng)一個方法被顯式拋出(通過聲明拋出InterruptedException)或隱式拋出(通過聲明/拋出一個原始異常)時,總是捕獲InterruptedException異常,并恢復(fù)中斷的標(biāo)志。
T getOrDefault(Callable supplier, T defaultValue) {
try {
return supplier.call();
}
catch (InterruptedException e) {
logger.error("Got interrupted while retrieving value.", e);
Thread.currentThread().interrupt();
return defaultValue;
}
catch (Exception e) {
logger.error("Got exception while retrieving value.", e);
return defaultValue;
}
}以上是“java如何捕獲InterruptedException錯誤”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
名稱欄目:java如何捕獲InterruptedException錯誤
本文URL:http://chinadenli.net/article30/ipcgso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、外貿(mào)建站、網(wǎng)站制作、全網(wǎng)營銷推廣、域名注冊、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)