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;
}
}
作者最新文章
ps怎么抠图
2026-10-20 17:22
PDF表格怎么转换成Excel?如何免费将PDF表格转成Excel?
2026-10-15 11:26
漫蛙manwa2在线阅读入口
2026-10-13 13:49
漫蛙漫画app下载安装包
2026-10-13 13:19
漫蛙MANWA2官方入口
2026-10-13 13:18
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































