Differences and Similarities between wait() and sleep() in Java
Both wait() and sleep() can pause a thread and enter waiting states, but wait() belongs to Object and requires synchronized blocks, releases the monitor lock, and must handle spurious wakeups, whereas sleep() is a Thread method that does not release locks and has simpler usage.
Question: What are the similarities and differences between wait() and sleep() in Java?
Similarities:
1. Both can pause a thread, moving it into WAITING or TIMED_WAITING states.
2. Both respond to interrupt signals and throw InterruptedException when interrupted.
Differences:
1. wait() is defined in Object , while sleep() is defined in Thread .
2. wait() must be called from a synchronized block; sleep() has no such requirement.
3. Calling wait() releases the monitor lock of the object; sleep() does not release any locks.
4. To avoid spurious wakeups, wait() should be used inside a while loop that checks the condition; sleep() does not need this pattern.
Method signatures:
public static void sleep(long millis, int nanos) throws InterruptedException public static void sleep(Duration duration) throws InterruptedException public final void wait() throws InterruptedException public final void wait(long timeoutMillis) throws InterruptedException public final void wait(long timeoutMillis, int nanos) throws InterruptedExceptionTypical usage of wait() :
synchronized (obj) { while (!condition && timeoutNotExceeded) { obj.wait(timeoutMillis, nanos); } // perform action based on condition or timeout }Additional question: Why are wait/notify/notifyAll defined in Object while sleep is defined in Thread ?
Because every Java object has an associated monitor lock, placing these methods in Object makes the monitor accessible to all objects; Thread already represents a thread, so its sleep behavior is naturally a thread method.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.