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?
A
waitcan be “woken up” by another thread callingnotifyon the monitor which is being waited on whereas asleepcannot. Also await(andnotify) must happen in a blocksynchronizedon the monitor object whereassleepdoes not:At this point the currently executing thread waits and releases the monitor. Another thread may do
(on the same
monobject) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.You can also call
notifyAllif 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 thewaitis in asynchronizedblock) and carry on – the others will then be blocked until they can acquire the monitor’s lock.Another point is that you call
waitonObjectitself (i.e. you wait on an object’s monitor) whereas you callsleeponThread.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 alwayswaitwhilst spinning on some condition as follows: