栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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-



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485888.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号