What is the difference between wait() and sleep() in Java?
sleep() pauses the current thread for a time and keeps any lock it holds. wait() must be called inside a synchronized block, releases that lock, and pauses until notify or notifyAll is called or the timeout ends.
Explain it simply
sleep() is a person dozing off in the doorway of a room: nobody else can get through, because they still hold the door. wait() is stepping out of the room and leaving the door free, with a note saying "call me when there is something to do".
Example
class Box {
private boolean ready = false;
synchronized void waitForItem() throws InterruptedException {
while (!ready) {
wait(); // releases the lock on this Box while waiting
}
System.out.println("item taken");
}
synchronized void putItem() {
ready = true;
notifyAll(); // wakes the waiting threads
}
}What to say in the interview
"sleep is a static method of Thread, needs no lock, and keeps held locks. wait is an instance method of Object, requires owning the object's monitor or it throws IllegalMonitorStateException, and gives up that monitor while waiting. I always call wait inside a while loop that rechecks the condition, because of spurious wakeups and because another thread may have changed the state."
Common mistakes
- Using
ifinstead ofwhilearound wait(). - Calling wait() or notify() outside synchronized.