问题描述
为什么要调用catch块中的方法Thread.currentThread.interrupt()
?
Why invoke the method Thread.currentThread.interrupt()
in the catch block?
推荐答案
这样做是为了保持状态.
当您捕捉到 InterruptedException
并吞下它时,您基本上可以防止任何更高级别的方法/线程组注意到中断.这可能会导致问题.
When you catch the InterruptedException
and swallow it, you essentially prevent any higher-level methods/thread groups from noticing the interrupt. Which may cause problems.
通过调用Thread.currentThread().interrupt()
,您可以设置线程的中断标志,因此更高级别的中断处理程序会注意到它并可以适当地处理它.
By calling Thread.currentThread().interrupt()
, you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.
Java 并发实践对此进行了更多讨论第 7.1.3 章:响应中断中的详细信息.它的规则是:
Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:
只有实现线程中断策略的代码才能吞下中断请求.通用任务和库代码永远不应该吞下中断请求.
这篇关于为什么在 catch InterruptException 块中调用 Thread.currentThread.interrupt()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!