sleep和wait

多线程问题中,经常问的一点就是sleep方法和wait方法的区别,如果没有看过源码,估计很多人死记硬背理解不了,还是老规矩,看源码理解。

1 注释的源码

Sleep

 Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

导致当前执行的线程休眠(暂时停止执行)指定的时间...线程不丢失任何监视器的所有权(我坐在座位上睡个觉,尽管我什么都不做但是座位还是我的)
Wait

Causes the current thread to wait until another thread invokes the {@link java.lang.Object#notify()} method or the {@link java.lang.Object#notifyAll()} method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
造成当前线程阻塞直到下面四种情况发生才会被打破阻塞状态:其他线程调用notify或者是notifyAll方法,或者其他线程干扰此线程,或者已经度过线程阻塞的时间。

这里写图片描述

这个时候就能看到两者的区别了,wait当前线程必须有对象的监视器,线程释放对监视器的所有权直到下面两种情况发生的时候才可以解除阻塞状态。

线程继续等待直到他重新获得对监视器的所有权才可以恢复运行。(我出去走走座位给别人坐了,等我回来之后等别人坐完我才可以坐)

2 代码的源码

Thread中静态方法:有java实现的

   public static void sleep(long millis, int nanos)
    throws InterruptedException{}
Object类中final native方法:需要C底层编写

public final native void wait() throws InterruptedException
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值