如果线程已被中断,Thread.sleep会抛出吗?

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

文档没有明确说明:

InterruptedException – 如果有任何线程中断了当前线程。 抛出此exception时,将清除当前线程的中断状态。

是的,它确实。

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

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

虽然我发现没有文件声明这是强制性的,但我发现在我的系统(32位客户端VM 1.7)上,尝试在设置中断的平面时hibernate。 测试代码:

 static volatile boolean ready = false; public static void main (final String... args) throws InterruptedException { Thread t = new Thread () { public void run () { while (!ready) { } try { Thread.sleep (1); System.out.println ("Not thrown!"); } catch (InterruptedException e) { System.out.println ("Thrown!"); } } }; t.start (); t.interrupt (); // remove this line to change the output ready = true; Thread.sleep (100); } 

没有。

该文档还说“如果在调用Object类的wait(),wait(long)wait(long,int)方法,或者join(),join(加入)时 阻塞了这个线程[我的重点] long),join(long,int),sleep(long)sleep(long,int),这个类的方法,然后它的中断状态将被清除,它将收到一个InterruptedException。“

这不包括你提到的情况。