Java的Thread.sleep什么时候会抛出InterruptedException异常?忽略它是否安全?我没有进行多线程操作,只是想在重试某些操作之前等待几秒钟。
Java的Thread.sleep什么时候会抛出InterruptedException异常?忽略它是否安全?我没有进行多线程操作,只是想在重试某些操作之前等待几秒钟。
通常情况下,您不应忽略异常。请参考以下论文:
Don't swallow interrupts
Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.
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-
InterruptedException
异常,意味着有些东西想要中断(通常是终止)该线程。这是通过调用线程的interrupt()
方法触发的。等待方法检测到这一点,并抛出InterruptedException
,因此catch代码可以立即处理终止请求,并且不必等到指定的时间结束。InterruptedException
会清除线程的中断状态,因此如果不正确处理该信息就会丢失。因此,我建议运行:} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// code for stopping current task so thread stops
}
再次设置状态后,结束执行。即使从未使用过,这样做也是正确的行为。
更好的方法可能是添加以下内容:
} catch (InterruptedException e) {
throw new RuntimeException("Unexpected interrupt", e);
}
这意味着将此代码块的语句转移到catch块中。基本上意味着它绝不能发生。因此,如果在可能发生该情况的环境中重复使用代码,则会对其进行投诉。
RuntimeException
异常。 - Evgeni Sergeev我强烈推荐《Java专家通讯》(The Java Specialists newsletter),该通讯刊登了一篇关于这个问题的有趣文章,并介绍了如何处理InterruptedException
。这篇文章非常值得阅读和消化。
Thread
类中的sleep()
和wait()
方法可能会抛出InterruptedException
异常。如果其他线程想要中断等待或睡眠的线程,就会发生这种情况。
在单线程代码中处理它的一种可靠而简单的方法是捕获并将其重新抛出为RuntimeException,以避免需要在每个方法中声明它。
InterruptedException
异常。interrupt()
方法时,就会发生InterruptedException
。它是一个已检查异常,在Java中许多阻塞操作都可能会抛出该异常。Thread.sleep()
中唤醒
- 等待锁的获取、等待I/O完成
- 等待另一个线程的计算结果等。
InterruptedException
通常会由所有阻塞方法抛出,以便处理并执行纠正操作。Thread.sleep()
- Thread.join()
- wait()
- BlockingQueue:
- put()
- take()
从个人经验来看,我只是将 thread.sleep()
改为 this.sleep()
InterruptedException
通常在睡眠被中断时抛出。
InterruptedException
是一个被捕获的异常,因此你必须在任何调用线程的join或sleep方法,或在对象上调用wait()
的方法中处理或声明此类型的异常,否则代码将无法编译。 - 8bitjunkie