我发现这种结构在 Thinking in java 的多线程章节中很流行:
public void run(){
try{
while(!Thread.currentThread().isInterrupted()){
// do something blocked like wait(), sleep() or I/O
}
}catch(InterruptedExeption e){
}
}
但是我现在认为,当且仅当阻塞的wait()
、sleep()
或I/O
时,while 循环才会退出> 抛出 InterruptedExeption
,为什么不使用 while(true)
呢?还是仅仅因为 Thread.currentThread().isInterrupted()
是规范的?
最佳答案
就其本身而言,检查中断是不必要的,因为 Runnable 所做的只是 hibernate 。但是正如您从评论中可以看出的那样,这旨在作为更大例程的模型。当 sleep 和等待抛出 InterruptedException 时,阻塞 I/O 调用(在注释中列出)不会,而不会等待或 sleep 的 CPU 密集型代码则不会。
Bruce E 在这里做的是提供一个模板供您遵循,它处理抛出 InterruptedException 的情况(他用它来退出循环),还处理不涉及 sleep 或等待的情况,不会抛出 InterruptedException。它让读者知道他们可以选择显式检查标志,并演示这样做的正确方法(与使用清除标志的中断方法相反)。
关于java - 为什么将 Thread.currentThread().isInterrupted() 与 try/catch 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45440886/