为什么在catch InterruptException块中调用Thread.currentThread.interrupt()? [英] Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?
问题描述
为什么在catch块中调用Thread.currentThread.interrupt()方法?
Why invoke the method Thread.currentThread.interrupt() in the catch block?
推荐答案
这是对保持状态。
当你捕获 InterruptException
并吞下它时,你基本上阻止任何更高级别方法/线程组注意到中断。这可能会导致问题。
When you catch the InterruptException
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 Concurrency in Practice 在第7.1.3节:响应中断中更详细地讨论了这一点。它的规则是:
Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:
只有实现线程中断策略的代码才可以吞下中断请求。通用任务和库代码永远不应该吞下中断请求。
Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.
这篇关于为什么在catch InterruptException块中调用Thread.currentThread.interrupt()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!