为什么要捕获 InterruptedException 来调用 Thread.currentThread.interrupt()?

发布于 2024-08-15 05:34:15 字数 422 浏览 4 评论 0原文

在Effective Java(第275页)中,有这样的代码段:

...
for (int i = 0; i < concurrency; i++) {
  executor.execute(new Runnable() {
    public void run() {
    ready.countDown();
    try {
      start.await();
      action.run();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      done.countDown();
    }
  }
}
...

捕获中断的异常只是为了重新引发它有什么用?为什么不让它飞呢?

In Effective Java (page 275), there is this code segment:

...
for (int i = 0; i < concurrency; i++) {
  executor.execute(new Runnable() {
    public void run() {
    ready.countDown();
    try {
      start.await();
      action.run();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      done.countDown();
    }
  }
}
...

What's the use of catching the interrupted exception just to re-raise it? Why not just let it fly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

娇女薄笑 2024-08-22 05:34:15

简单的答案是,InterruptedException 是一个已检查异常,它不在 Runnable.run 方法(或 Executable.execute())的签名中代码>方法)。所以你必须抓住它。一旦你捕获了它,建议你调用 Thread.interrupt() 来设置中断标志......除非你真的打算压制中断。

The simple answer is that InterruptedException is a checked exception and it is not in the signature of the Runnable.run method (or the Executable.execute() method). So you have to catch it. And once you've caught it, calling Thread.interrupt() to set the interrupted flag is the recommended thing to do ... unless you really intend to squash the interrupt.

恋竹姑娘 2024-08-22 05:34:15

有时你不能忽略异常,你必须捕获它。主要是当您重写无法根据其签名抛出 InterruptedException 的方法时,会发生这种情况。例如,这种方法通常用在 Runnable.run() 方法中。

Sometimes you can't ignore exception and you must catch it. Mainly this happens when you override method which can't throw InterruptedException in accordance with its signature. For example, this approach is usually used in Runnable.run() method.

作死小能手 2024-08-22 05:34:15

如果任务被取消,执行器可以中断任务,但它会清除任务之间的中断标志,以避免一个已取消的任务中断不相关的任务。

因此,如果当前线程确实做了任何事情,那么在这里中断它将会很危险。

解决此问题的一种更简单的方法是使用 Callable 或忽略中断。

此外,捕获并记录 try/catch 块中引发的任何错误或异常是一个好主意,否则异常/错误将被丢弃,并且您的程序可能会失败,但您不会知道它是什么或为什么。

The executor can interrupt tasks if they are cancelled but it clears the interrupted flag between tasks to avoid one cancelled task interrupting an unrelated task.

As such, interrupting the current thread here would be dangerous if it actually did anything.

A simpler way around this is to use Callable or ignore the interrupt.

Additionally it is a good idea to catch and log any error or exception thrown in the try/catch block otherwise the exception/error will be discarded and your program could be failing but you won't know it is or why.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文