线程因睡眠而暂停后会发生什么?

发布于 2024-11-05 03:48:27 字数 187 浏览 0 评论 0原文

我有以下代码,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

楠木可依 2024-11-12 03:48:27

不,InterruptedException 在正常流程中不会抛出,但是当在线程上调用 interrupt() 时可能会发生(例如,通过一些其他代码试图中断此线程的正常执行流程)线)。
通常,执行只是在 sleep 语句之后的行中继续。

no, InterruptedException is not thrown during normal flow, but might happen when interrupt() 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.

拥醉 2024-11-12 03:48:27

如果在睡眠期间调用interrupt方法。 catch 只与 try 的代码相关,之后就不起作用了。

If the interrupt method is called during the sleep time. The catch is relevant only for the code of try, after that it has no effect.

小糖芽 2024-11-12 03:48:27

如果线程被中断,则抛出 InterruptedException,这可能发生在睡眠期间或可能发生在不久前。在大多数情况下,当您不希望出现 InterruptedException 并且不想处理它时,最好这样做,

try{
    sleep(500);
}catch(InterruptedException e){
    Thread.currentThread().interrupt();
}

这样中断就不会丢失。

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

try{
    sleep(500);
}catch(InterruptedException e){
    Thread.currentThread().interrupt();
}

so the interrupt is not lost.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文