如何理解'notify you twice about a task being interrupted'

how to understand 'notify you twice about a task being interrupted'

我最近在阅读 Java 中的思考。在 'Checking for an interrupt' 章节中,它说 'by calling interrupted( ). This not only tells you whether interrupt( ) has been called, it also clears the interrupted status. Clearing the interrupted status ensures that the framework will not notify you twice about a task being interrupted.'

这个怎么理解?通知中断两次的后果是什么?

很难给出一个简单的答案,因为中断需要线程的协作:结果取决于您的应用程序如何处理中断。

如果你幂等地处理它们,通知两次也没关系;同样,如果以非幂等方式处理,它确实如此。

例如,线程必须检查它们是否已被中断,以便知道它们应该尝试停止它们正在做的事情。您可能会看到类似这样的内容:

if (Thread.interrupted()) {
  throw new InterruptedException();
}

中断标志和 InterruptedException 是指示中断的不同方式。像上面那样做意味着只有一件事表明在捕获异常的地方被中断——异常被捕获的事实——所以你可以完全处理那里的中断并继续。

如果你在那里使用了 isInterrupted(),这不会清除标志:

if (Thread.currentThread().isInterrupted()) {
  throw new InterruptedException();
}

您将抛出并接住 InterruptedException,但仍会设置中断标志。如果您随后调用了自己检查中断的东西(例如 Thread.sleep()):

// Terrible code! This is purely to demonstrate a point.
try {
  try {
    if (Thread.currentThread().isInterrupted()) { // Try replacing with interrupted().
      throw new InterruptedException();
    }
  } catch (InterruptedException e) {
    Thread.sleep(100);
    System.out.println("I slept, I woke up");
  }
} catch (InterruptedException ee) {
  System.out.println("Oh no not again!");
}

由于中断标志,即使在捕获和睡眠之间实际上没有发生新的中断,也会立即抛出 InterruptedException