给定一个线程在没有被阻塞的情况下被中断(即没有抛出 InterruptedException),该线程稍后尝试休眠时是否会抛出 InterruptedException?
该文档没有明确说明这一点:
InterruptedException - 如果任何线程中断了当前线程。抛出此异常时清除当前线程的中断状态。
给定一个线程在没有被阻塞的情况下被中断(即没有抛出 InterruptedException),该线程稍后尝试休眠时是否会抛出 InterruptedException?
该文档没有明确说明这一点:
InterruptedException - 如果任何线程中断了当前线程。抛出此异常时清除当前线程的中断状态。
是的,它确实。
文档在这一点上可能不是很清楚,但这很容易测试(例如,请参阅下面的您自己的答案)和查看规范(HotSpot)实现。Thread.sleepos:sleep
在启动睡眠过程之前检查中断,如您在此处看到的(查找os:sleep
)。
如果不是这种情况,中断将或多或少无法使用。如果他们碰巧在任何sleep()
呼叫之外到达,他们就会丢失,因为随后的sleep()
呼叫会忽略它们。你甚至不能重新中断线程,因为它已经被中断了。
虽然我没有找到说明这是强制性的文档,但我发现在我的系统(32 位客户端 VM 1.7)上,在设置中断平面时尝试睡眠确实会抛出异常。测试代码:
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。”
这不包括你提到的情况。