调用Thread.sleep()与*中断状态*设置?

Java文档在这一点上并不清楚。 如果调用Thread.sleep() 之前调用Thread上的中断会发生什么:

//interrupt reaches Thread here try { Thread.sleep(3000); } catch (InterruptedException e) { return; } 

是否会抛出InterruptedException ?

请指向相关文档。

是的,它会抛出exception。 根据Thread.sleep的javadoc,方法:

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

在这种情况下,’has’是指称中断状态的非正式方式。 令人遗憾的是它是非正式的 – 如果某个地方的规范应该是精确和明确的,那么它无处不在,但它首先是线程原语。

中断状态机制一般工作的方式是,如果一个线程在不可中断的情况下收到中断(因为它正在运行),那么中断基本上是等到线程中断,此时它突然导致InterruptedException的。 这是该机制的一个例子。

一个线程可以在任何时间点被中断,但是在该线程专门用Thread.currentThread().isInterrupted()或者当它到达时 ,或者已经被调用阻止时,它将没有任何影响Thread.currentThread().isInterrupted() Thread.sleep(long)Object.wait(long)或其他标准JDK方法,它们抛出InterruptedException例如java.nio包中的那些。 当您捕获InterruptedException或显式调用Thread.interrupted()时,将重置线程的中断状态(请参阅该难以捉摸的方法的文档)。

这篇JavaSpecialists文章应该更多地解释线程中断如何工作以及如何正确处理它们。

您可以使用以下类来测试行为。 在这种情况下,循环不会中断,并且线程在进入睡眠状态时会死亡。

公共类TestInterrupt {

 public static void main(String[] args) throws InterruptedException { Thread t = new Thread(){ public void run(){ System.out.println("hello"); try { for (int i = 0 ; i < 1000000; i++){ System.out.print("."); } Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("interrupted"); e.printStackTrace(); } } }; t.start(); Thread.sleep(100); System.out.println("about to interrupt."); t.interrupt(); } 

}

InterruptedException的文档似乎表明它可以在其他时间被中断

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/InterruptedException.html

当线程等待,hibernate或以其他方式暂停很长一段时间时抛出,另一个线程使用Thread类中的中断方法中断它

此外,由于它是一个经过检查的exception,它只会被声明它的方法抛出。 看到

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#interrupt ()