java sleep异常_Java的Thread.sleep何时会引发InterruptedException?

不要吞下中断

有时,抛出InterruptedException并不是一种选择,例如Runnable定义的任务调用可中断方法时。在这种情况下,您不能抛出InterruptedException,但也不想执行任何操作。当阻塞方法检测到中断并引发InterruptedException时,它将清除中断状态。如果捕获了InterruptedException但无法将其抛出,则应保留发生中断的证据,以便调用堆栈中更高级别的代码可以了解该中断并在需要时对其进行响应。可以通过调用interrupt()来“重新中断”当前线程来完成此任务,如清单3所示。至少,每当您捕获InterruptedException并且不抛出该异常时,请在返回之前重新中断当前线程。

public class TaskRunner implements Runnable {

private BlockingQueue queue;

public TaskRunner(BlockingQueue 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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值