Java的Thread.sleep什么时候抛出InterruptedException?

Man*_*nki 106 java multithreading sleep interrupted-exception interruption

Java的Thread.sleep什么时候抛出InterruptedException?忽视它是否安全?我没有做任何多线程.我只是想等几秒钟再重试一些操作.

Bra*_*lor 38

您通常不应忽略该异常.看看下面的论文:

不要吞下中断

有时抛出InterruptedException不是一个选项,例如当Runnable定义的任务调用可中断方法时.在这种情况下,您不能重新抛出InterruptedException,但您也不想做任何事情.当阻塞方法检测到中断并抛出InterruptedException时,它会清除中断状态.如果捕获InterruptedException但无法重新抛出它,则应保留中断发生的证据,以便调用堆栈上的代码可以了解中断并在需要时响应它.这个任务是通过调用interrupt()来"重新中断"当前线程来完成的,如清单3所示.至少,每当你捕获InterruptedException并且不重新抛出它时,在返回之前重新中断当前线程.

public class TaskRunner implements Runnable {
    private BlockingQueue<Task> queue;

    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    }

    public void run() { 
        try {
             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         }
         catch (InterruptedException e) { 
             // Restore the interrupted status
             Thread.currentThread().interrupt();
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里查看整篇论文:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-


Chr*_*ian 37

如果InterruptedException抛出它意味着某些东西想要中断(通常终止)该线程.这是通过调用threads interrupt()方法触发的.wait方法检测到并抛出一个,InterruptedException因此catch代码可以立即处理终止请求,而不必等到指定的时间结束.

如果您在单线程应用程序(以及某些多线程应用程序)中使用它,则永远不会触发该异常.通过使用空catch子句来忽略它我不建议.抛出会InterruptedException清除线程的中断状态,因此如果处理不当,则信息会丢失.因此我建议运行:

} catch (InterruptedException e) {
  Thread.currentThread().interrupt();
  // code for stopping current task so thread stops
}
Run Code Online (Sandbox Code Playgroud)

哪个再次设置状态.之后,完成执行.这将是正确的行为,甚至从未使用过.

可能更好的是添加这个:

} catch (InterruptedException e) {
  throw new RuntimeException("Unexpected interrupt", e);
}
Run Code Online (Sandbox Code Playgroud)

...对catch块的声明.这基本上意味着它永远不会发生.因此,如果代码在可能发生的环境中重用,它会抱怨它.

  • Java中的断言默认为[off](http://stackoverflow.com/a/2758645/1143274).所以最好抛出一个`RuntimeException`. (5认同)

Bri*_*new 12

Java专家通讯(我可以毫无保留地推荐)有一篇有趣的文章,以及如何处理InterruptedException.这非常值得阅读和消化.

  • 它说什么? (7认同)