简体   繁体   English

在InterruptedException的catch子句中中断线程的原因是什么?

[英]What is the reason for interrupting the thread in the catch clause of InterruptedException?

I'm reading J. Bloch's Effective Java and now I'm at the section which explains about Concurrency. 我正在阅读J. Bloch的Effective Java,现在在解释并发的部分中。 The writer has provided the following example (Some modifications were applied to make it simpler): 作者提供了以下示例(进行了一些修改以使其更简单):

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();
        }
    }
});

It's not clear that why we interrupt the Thread that already was interrupted? 不清楚为什么我们要中断已经被中断的线程? Couldn't you get a little explanation about what kind of troubles we may run into if we omit such interrupting? 如果我们忽略这样的打扰,您是否能对我们会遇到什么样的麻烦有一点解释?

Yes, it's right. 是的这是对的。

When an InterruptedException is thrown from a blocking method, the interrupt flag is cleared. 从阻塞方法引发InterruptedException ,将清除中断标志。

The right thing to do is to reset the interrupt flag (ie interrupt again) and stop running ASAP. 正确的做法是重置中断标志(即再次中断)并尽快停止运行。 Resetting the interrupt flag is necessary to let the executor (or any other calling code) know that the thread has been interrupted, and thus allow it to stop running. 必须重置中断标志,以使执行程序(或任何其他调用代码)知道线程已被中断,从而允许其停止运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM