为什么要在catch块中调用Thread.currentThread.interrupt()
方法呢?
发布于 2011-07-19 20:14:01
我认为这个代码示例让事情变得更清楚了。完成这项工作的类:
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();
}
}
尝试在不重新设置状态的情况下调用interrupt。
发布于 2011-02-05 20:33:54
我会认为这是一种糟糕的做法,或者至少有一点风险。通常,更高级别的方法不会执行阻塞操作,并且它们永远不会在那里看到InterruptedException
。如果你在执行可中断操作的每个地方都屏蔽它,你永远不会得到它。
Thread.currentThread.interrupt()
和不引发任何其他异常或以任何其他方式发送中断请求(例如,在线程的主循环中设置interrupted
局部变量)的唯一理由是,您确实无法对异常做任何事情,就像在finally
块中一样。
如果您想更好地理解Thread.currentThread.interrupt()
调用的含义,请参阅Péter Török的答案。
https://stackoverflow.com/questions/4906799
复制相似问题