Java之也谈sleep()和wait()

讨论sleep()和wait()的很多文章流传蛮广,甚至有些都是错误的。那我我也谈谈自己的观点。

首先sleep(),直接看官方文档

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

加红的文字表明比如在synchronized (obj){...}语句块中执行Thread.sleep()不会丢失obj锁。


接着wait(),

Causes the current thread to wait until another thread invokes the  notify()  method or the  notifyAll()  method for this object. In other words, this method behaves exactly as if it simply performs the call  wait(0) .

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the  notify  method for a description of the ways in which a thread can become the owner of a monitor.
加红2段文字都说明了,要想调用wait()必须拥有object's monitor。换一种说法,必须在同步语句块或者同步方法中执行wait()。
实测中如果不满足上述条件,强行调用并运行会抛出Exception in thread "main" java.lang.IllegalMonitorStateException。

加蓝的文字说wait()方法一般在循环中使用,这个搜搜很多apache源码看看基本都是如此。



tips:

         我说网上文章是错误的是关于时间片的说法,说wait()不占用时间片,sleep()占用时间片。如果是真的,不仅官方文档中对这么重要的事情,提都不提实属不该,而且我实测中,无论是wait()或者sleep()都是释放了cpu的控制权的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值