如果线程已被中断,Thread.sleep会抛出吗? [英] Does Thread.sleep throw if the thread was already interrupted?

查看:265
本文介绍了如果线程已被中断,Thread.sleep会抛出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个在没有被阻塞时被中断的线程(即没有抛出InterruptedException),该线程在以后尝试睡眠时是否会抛出InterruptedException?

Given a thread which was interrupted while it was not blocked (i.e. no InterruptedException was thrown), does that thread throw an InterruptedException when it later attempts to sleep?

文档确实没有明确说明:


InterruptedException - 如果有任何线程中断了当前线程。抛出此异常时,当前线程的中断状态被清除。

InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.


推荐答案

是的,确实如此。

关于这一点,文档可能并不十分清楚,但这很容易进行测试(例如,请参阅下面的答案),以及看到规范(HotSpot)实现。 Thread.sleep shell发送到 os:sleep ,它会在启动睡眠过程之前检查中断,如你所见这里(寻找 os:sleep )。

The documentation perhaps isn't crystal clear on that point, but this is easy to both test (see the your own answer below, for example), and to see the canonical (HotSpot) implementation. Thread.sleep shells out to os:sleep which checks interruption before staring the sleep process as you can see here (look for os:sleep).

如果不是这种情况,中断或多或少都不可能使用。如果他们碰巧在任何 sleep()调用之外到达,他们将会丢失,因为后续 sleep()调用将被忽略他们。你甚至无法重新中断线程,因为它已经被中断了。

If this wasn't the case, interrupts would be more or less impossible to use. If they happened to arrive outside of any sleep() call they would be lost as subsequent sleep() calls would ignore them. You couldn't even re-interrupt the thread because it is already interrupted.

这篇关于如果线程已被中断,Thread.sleep会抛出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆