Java之也谈sleep()和wait()

来源:互联网 发布:中国有嘻哈冠军知乎 编辑:程序博客网 时间:2024/05/21 14:10

讨论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