小编给大家分享一下java如何捕获InterruptedException错误,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
捕获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错误”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。