InterruptedException的catch子句中线程中断的原因是什么?
What is the reason for interrupting the thread in the catch clause of InterruptedException?
我正在阅读 J. Bloch 的 Effective Java,现在我在解释并发的部分。作者提供了以下示例(进行了一些修改以使其更简单):
Runnable action;
//...
executor.execute(new Runnable() {
public void run() {
ready.countDown();
try {
start.await();
action.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // <------- Here
} finally {
done.countDown();
}
}
});
不清楚为什么要中断已经被中断的Thread?你能不能解释一下,如果我们忽略这种打扰,我们可能 运行 会遇到什么样的麻烦?
是的,没错。
当从阻塞方法中抛出 InterruptedException
时,中断标志被清除。
正确的做法是重置中断标志(即再次中断)并尽快停止 运行。重置中断标志对于让执行程序(或任何其他调用代码)知道线程已被中断是必要的,从而允许它停止 运行.
我正在阅读 J. Bloch 的 Effective Java,现在我在解释并发的部分。作者提供了以下示例(进行了一些修改以使其更简单):
Runnable action;
//...
executor.execute(new Runnable() {
public void run() {
ready.countDown();
try {
start.await();
action.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // <------- Here
} finally {
done.countDown();
}
}
});
不清楚为什么要中断已经被中断的Thread?你能不能解释一下,如果我们忽略这种打扰,我们可能 运行 会遇到什么样的麻烦?
是的,没错。
当从阻塞方法中抛出 InterruptedException
时,中断标志被清除。
正确的做法是重置中断标志(即再次中断)并尽快停止 运行。重置中断标志对于让执行程序(或任何其他调用代码)知道线程已被中断是必要的,从而允许它停止 运行.