捕获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;
}
}以上就是java如何捕获InterruptedException错误的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号