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