问九:源码层面解析Thread.sleep()为什么需要抛异常?

结合此篇文章进行阅读:InterruptedExcption详细分析

导入:

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方法需要调用的线程支持

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值