如果一个线程在未被阻塞时被中断(即没有抛出InterruptedException ),那么该线程在以后尝试休眠时会抛出InterruptedException吗?
文档没有清楚地说明这一点:
InterruptedException -如果任何线程中断了当前线程。当引发此异常时,将清除当前线程的中断状态。
发布于 2014-05-17 10:51:55
是的,确实如此。
文档在这一点上可能并不十分清楚,但这两种测试都很容易(例如,请参见下面的答案),也很容易看到规范(HotSpot)实现。Thread.sleep提供给os:sleep,它在启动睡眠过程之前检查中断,因为您可以看到这里 (查找os:sleep)。
如果不是这样的话,中断或多或少是不可能使用的。如果它们碰巧到达任何sleep()调用之外,它们就会丢失,因为后续的sleep()调用会忽略它们。您甚至不能重新中断线程,因为它已经被中断了。
发布于 2014-05-17 10:15:50
虽然我没有发现说明这是强制性的文档,但我发现在我的系统(32位客户机VM1.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);
}发布于 2014-05-17 10:15:33
不是的。
文档还指出,“如果这个线程在调用对象类的等待()、等待(长)或等待(长,int)方法时阻塞了我的重点,或者join()、join(long)、join(long、int)、join(long、int)或sleep(long,int),那么它的中断状态将被清除并接收InterruptedException。”
不包括你提到的那个案子。
https://stackoverflow.com/questions/23710025
复制相似问题