Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is the Difference between wait() and sleep()

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?
by

2 Answers

RoliMishra
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(); }
kshitijrana14
One key difference not yet mentioned is that while sleeping a Thread does not release the locks it holds, while waiting releases the lock on the object that wait() is called on.
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}

synchronized(LOCK) {
LOCK.wait(); // LOCK is not held
}

Login / Signup to Answer the Question.