为什么要在catch block 中调用Thread.currentThread.interrupt()
方法?
最佳答案
这样做是为了保持状态。
当您捕获 InterruptedException
并将其吞下时,您基本上可以防止任何更高级别的方法/线程组注意到中断。这可能会导致问题。
通过调用Thread.currentThread().interrupt()
,你设置了线程的中断标志,所以更高级别的中断处理程序会注意到它并可以适本地处理它。
Java Concurrency in Practice在第 7.1.3 章:响应中断中更详细地讨论了这一点。它的规则是:
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.
关于java - 为什么在 catch InterruptException block 中调用 Thread.currentThread.interrupt()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4906799/