为什么要捕获InterruptedException来调用Thread.currentThread.interrupt()? [英] Why would you catch InterruptedException to call Thread.currentThread.interrupt()?

查看:142
本文介绍了为什么要捕获InterruptedException来调用Thread.currentThread.interrupt()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Effective Java(第275页)中,有以下代码段:

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?

推荐答案

简单的答案是 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.

这篇关于为什么要捕获InterruptedException来调用Thread.currentThread.interrupt()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆