wait()和sleep()之间的区别

wait()和sleep()之间的区别

问题描述:

线程中的 wait() sleep()有什么区别?

What is the difference between a wait() and sleep() in Threads?

我的理解是 wait() -ing Thread仍处于运行模式并使用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 等待 可以被另一个调用 在正在等待的监视器上通知 ,而 睡眠 不能。另外等待(和通知)必须在块 synchronized $ c $中发生c>在监视器对象上而 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 如果监视器上有多个线程在等待 - 这会唤醒所有人。但是,只有一个线程能够获取监视器(请记住等待位于 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.

另一点是你打电话给等待 on 对象 本身(即你在对象的监视器上等待),而你在 sleep https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html\"rel =noreferrer> 主题

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.

还有一点是你可以从等待虚假唤醒 (即等待恢复的线程没有明显原因)。您应该始终等待,同时在某种情况下旋转,如下所示:

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(); }
}