wait() 和 sleep() 的区别 [英] Difference between wait() and sleep()
问题描述
线程中的 wait()
和 sleep()
有什么区别?
What is the difference between a wait()
and sleep()
in Threads?
我是否理解 wait()
-ing 线程仍处于运行模式并使用 CPU 周期,但 sleep()
-ing 不消耗任何 CPU 周期正确吗?
Is my understanding that a wait()
-ing Thread is still in running mode and uses CPU cycles but a sleep()
-ing does not consume any CPU cycles correct?
为什么我们有 wait()
和 sleep()
:它们的实现在较低级别有何不同?
Why do we have both wait()
and sleep()
: how does their implementation vary at a lower level?
推荐答案
A wait
可以被另一个调用 notify
在正在等待的监视器上,而 sleep
不能.此外,wait
(和 notify
)必须发生在监视器对象上的 synchronized
块中,而 sleep
不会:
A wait
can be "woken up" by another thread calling notify
on the monitor which is being waited on whereas a sleep
cannot. Also a wait
(and notify
) must happen in a block synchronized
on the monitor object whereas sleep
does not:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
此时当前正在执行的线程等待并释放监视器.另一个线程可能会
At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (mon) { mon.notify(); }
(在同一个 mon
对象上)和第一个线程(假设它是在监视器上等待的唯一线程)将被唤醒.
(on the same mon
object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
您也可以调用notifyAll
如果监视器上等待的线程不止一个——这将唤醒所有线程.但是,只有一个线程能够获取监视器(请记住,wait
位于 synchronized
块中)并继续执行——然后其他线程将被阻塞,直到他们可以获取监视器的锁.
You can also call notifyAll
if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait
is in a synchronized
block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
另一点是您在 Object
本身(即您在对象的监视器上等待),而您在 sleep="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html" rel="noreferrer">Thread
.
Another point is that you call wait
on Object
itself (i.e. you wait on an object's monitor) whereas you call sleep
on Thread
.
还有一点是,您可以从 wait
获得虚假唤醒(即正在等待的线程无缘无故地恢复).您应该始终等待
同时在某些条件下旋转,如下所示:
Yet another point is that you can get spurious wakeups from wait
(i.e. the thread which is waiting resumes for no apparent reason). You should always wait
whilst spinning on some condition as follows:
synchronized {
while (!condition) { mon.wait(); }
}
这篇关于wait() 和 sleep() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!