导入:

Thread.sleep()抛的是InterruptedException,这个错误在源码中的注释为:

* Thrown when a thread is waiting, sleeping, or  otherwise occupied,

* and the thread is interrupted, either before or  during the activity.

* Occasionally a method may wish to test whether  the current

* thread has been interrupted, and if so, to  immediately throw

* this exception.

 

概述:

这个问题实际上是对interrupt方法的一个升级版,先解释interrupt,再解释源码中的判断

 

源码分析:

通过查看sleep的源码发现,它其实是一个native方法,参考前面run与start区别,来进行源码查找与分析

jvm源码:

http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/111b95ad4584/src/share/vm/prims/jvm.cpp

Thread中native方法的源码,调用了JVM_Sleep方法:

http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/f0b93fbd8cf8/src/share/native/java/lang/Thread.c

可以看到,sleep这个方法在源码中是会判断当前进程是否处于interrupted状态的,也符合之前所所说的interrupt方法需要调用的线程支持