您好,欢迎访问一九零五行业门户网

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错误的详细内容。
其它类似信息

推荐信息