我的代码中出现中断异常,我正在尝试了解原因。
我试图通过调用 FilesUtils.filesMethod() 在我的文件系统中的某个位置创建文件。
如果我收到 IOException,我会尝试 hibernate 100 毫秒。 在 sleep 期间我需要检查我是否被打断(因为 InterruptedException 是 sleep 时的检查异常)。
如果是这样,我打印“Got interrupted”并将当前线程的中断标志设置为 true。
我的日志中显示“被打扰了”。
在我的代码中没有任何地方有这个线程的命令 interrput()。
会是什么?
这个 senario 是否有意义:
ilesUtils.filesMethod() 的方法抛出 InterruptedIOException,因为流已在线程脚下关闭。此外,此 InterruptedIOException 将 Interrupted 标志设置为 true。
我在 catch 中捕获了 InterruptedIOException (IOException e)。
sleep 检查中断标志是否为真。它是(见 1)所以它抛出 InterruptedException。
会是这样吗?
try {
FilesUtils.filesMethod();
break;
} catch (IOException e) {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e1) {
log.info("Got interrupted", e1);
Thread.currentThread().interrupt();
}
}
最佳答案
在不知道FilesUtils.filesMethod()
的实现细节的情况下,我们只能猜测这里发生了什么。
但只是抛出 InterruptedIOException
不会导致设置中断标志。
我猜 FilesUtils.filesMethod()
设置了 interrupt在抛出 InterruptedIOException
之前标记,然后 sleep
方法抛出 InterruptedException
(因为设置了中断标志)。
您可以使用Thread.interrupted() 清除中断标志。在调用 sleep 方法之前(如果您希望在这种情况下能够休眠)。所以 sleep 方法不会抛出 InterruptedException
。(如果线程没有再次被中断)
关于java - InterruptedIOException 是否将线程的 Interrupted 标志设置为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689513/