java如何捕获InterruptedException错误
作者:BrightSoul
时间:2023-05-01
浏览:1
捕获InterruptedException错误请检查下面的代码片段:publicclassTaskimplementsRunnable{privatefinalBlockingQueuequeue=...;@Overridepublicvoidrun(){while(!Thread.currentThread().isInterrupted()){Stringresult=getOrDefault(()->queue.poll(1L,TimeUnit.MINUTES),"default");//dosm
本文目录
捕获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;
}
}
}代码的问题是,在等待队列中的新元素时,是不可能终止线程的,因为中断的标志永远不会被恢复:
1.运行代码的线程被中断。
2.BlockingQueue # poll()方法抛出InterruptedException异常,并清除了中断的标志。
3.while中的循环条件 (!Thread.currentThread().isInterrupted())的判断是true,因为标记已被清除。
为了防止这种行为,当一个方法被显式抛出(通过声明抛出InterruptedException)或隐式抛出(通过声明/抛出一个原始异常)时,总是捕获InterruptedException异常,并恢复中断的标志。
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;
}
}
作者最新文章
Unfold如何预览压缩包内文件清单
2026-12-02 23:42
Badgeify怎么添加软件图标到Mac菜单栏
2026-12-02 23:38
红果短剧剧集页面能看哪些信息?简介、标签与同类推荐解读
2026-12-02 20:32
漫蛙漫画网页入口及台版资源汇总
2026-12-02 09:53
漫蛙manwa漫画APP下载入口及网页版链接
2026-12-01 14:47
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多





































