The wait() and sleep() methods in Java serve different purposes in concurrency and thread management. Here’s a detailed breakdown of their differences:
1. Class and Usage
wait()
sleep()
Defined in Object class.
Defined in Thread class.
Used for thread synchronization (inter-thread communication).
Used to pause the current thread for a specified time.
2. Lock Behavior
wait()
sleep()
Releases the object’s lock when called (allows other threads to acquire the lock).
Does not release any locks (thread retains ownership of locks).
Must be called within a synchronized block/method (to hold the lock initially).
Can be called without synchronization.
3. Awakening Mechanism
wait()
sleep()
Wakes up when another thread calls notify()/notifyAll() on the same object, or after a timeout (if specified).
Wakes up automatically after the specified time elapses.
Example: wait(1000) waits up to 1 second for notification.
Example: sleep(1000) sleeps exactly 1 second.
4. Exception Handling
wait()
sleep()
Throws InterruptedException if the waiting thread is interrupted.
Also throws InterruptedException if interrupted during sleep.
5. Example Scenarios
Using wait() for Thread Coordination
synchronized (sharedObject) {
while (conditionNotMet) {
sharedObject.wait(); // Releases lock and waits
}
// Proceed when notified
}