Java的Thread.sleep何时会引发InterruptedException?

Java的Thread.sleep何时会引发InterruptedException?,第1张

Java的Thread.sleep何时会引发InterruptedException?

通常,您不应忽略该异常。看一下以下论文:

不要吞下中断

有时,抛出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();         }    }}

*从不要吞下中断


请在此处查看全文:

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



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5478027.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存