What is the difference between a 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?
Best Answer
A
wait
can be "woken up" by another thread callingnotify
on the monitor which is being waited on whereas asleep
cannot. Also await
(andnotify
) must happen in a blocksynchronized
on the monitor object whereassleep
does not:At this point the currently executing thread waits and releases the monitor. Another thread may do
(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 thewait
is in asynchronized
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
onObject
itself (i.e. you wait on an object's monitor) whereas you callsleep
onThread
.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 alwayswait
whilst spinning on some condition as follows: