线程因睡眠而暂停后会发生什么?
我有以下代码,
try{
sleep(500);
}catch(InterruptedException e){}
当线程完成休眠或在该线程上调用 interrupt
方法时,是否会引发 InterruptedException
?
I have following code
try{
sleep(500);
}catch(InterruptedException e){}
Is the InterruptedException
thrown when the thread has finished sleeping or when interrupt
method is called on that thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,
InterruptedException
在正常流程中不会抛出,但是当在线程上调用interrupt()
时可能会发生(例如,通过一些其他代码试图中断此线程的正常执行流程)线)。通常,执行只是在 sleep 语句之后的行中继续。
no,
InterruptedException
is not thrown during normal flow, but might happen wheninterrupt()
is called on the thread (e.g. by some other code trying to interrupt normal execution flow of this thread).Normally execution simply continues in the line after the sleep statement.
如果在睡眠期间调用
interrupt
方法。catch
只与try
的代码相关,之后就不起作用了。If the
interrupt
method is called during the sleep time. Thecatch
is relevant only for the code oftry
, after that it has no effect.如果线程被中断,则抛出 InterruptedException,这可能发生在睡眠期间或可能发生在不久前。在大多数情况下,当您不希望出现 InterruptedException 并且不想处理它时,最好这样做,
这样中断就不会丢失。
InterruptedException is throw if the Thread is interrupted which may happen during the sleep or which might have happened a while ago. In most cases when you do not expect the InterruptedException and don't want to handle it it ist better to
so the interrupt is not lost.