gotchajavaCritical
Difference between "wait()" vs "sleep()" in Java
Viewed 0 times
javabetweendifferencesleepwait
Problem
What is the difference between a
Is my understanding that a
Why do we have both
How does their implementation vary at a lower level?
wait() and sleep() in Threads?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?Why do we have both
wait() and sleep()?How does their implementation vary at a lower level?
Solution
A
At this point the currently executing thread waits and releases the monitor. Another thread may do
(on the same
You can also call
Another point is that you call
Yet another point is that you can get spurious wakeups from
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(); }(on the same
mon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up. 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.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(); }
}Code Snippets
Object mon = ...;
synchronized (mon) {
mon.wait();
}synchronized (mon) { mon.notify(); }synchronized {
while (!condition) { mon.wait(); }
}Context
Stack Overflow Q#1036754, score: 920
Revisions (0)
No revisions yet.