为什么要在 catch InterruptException 块中调用 Thread.currentThread.interrupt() ?
2022-08-31 06:28:17
为什么要调用 catch 块中的方法?Thread.currentThread.interrupt()
为什么要调用 catch 块中的方法?Thread.currentThread.interrupt()
这样做是为了保持状态。
当您捕获并吞咽它时,您基本上可以防止任何更高级别的方法/线程组注意到中断。这可能会导致问题。InterruptedException
通过调用 ,您可以设置线程的中断标志,以便更高级别的中断处理程序会注意到它并可以适当地处理它。Thread.currentThread().interrupt()
Java 并发实践在第 7.1.3 章:响应中断中更详细地讨论了这一点。其规则是:
只有实现线程中断策略的代码才能吞噬中断请求。通用任务和库代码不应吞并中断请求。
我认为这个代码示例使事情变得有点清晰。完成工作的类:
public class InterruptedSleepingRunner implements Runnable {
@Override
public void run() {
doAPseudoHeavyWeightJob();
}
private void doAPseudoHeavyWeightJob() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
// You are kidding me
System.out.println(i + " " + i * 2);
// Let me sleep <evil grin>
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread interrupted\n Exiting...");
break;
} else {
sleepBabySleep();
}
}
}
protected void sleepBabySleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
课程:Main
public class InterruptedSleepingThreadMain {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new InterruptedSleepingRunner());
thread.start();
// Giving 10 seconds to finish the job.
Thread.sleep(10000);
// Let me interrupt
thread.interrupt();
}
}
尝试在不设置状态的情况下调用中断。