为什么在catch块中调用方法Thread.currentThread.interrupt()
?
为什么在catch块中调用方法Thread.currentThread.interrupt()
?
这是对keep state人做的.
当你抓住InterruptedException
并吞下它时,你基本上可以防止任何更高级别的方法/线程组注意到中断.这可能会造成问题.
通过调用Thread.currentThread().interrupt()
,您可以设置线程的中断标志,这样更高级别的中断处理程序就会注意到它,并可以适当地处理它.
Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:
只有实现线程中断策略的代码才能接受中断请求.通用任务和库代码不应该吞噬中断请求.