wait() vs sleep() vs join() in Java
Introduction
In Java multithreading, wait(), sleep(), and join() are commonly asked about in interviews.
They all affect thread execution but serve different purposes. Understanding their differences is crucial for writing correct concurrent code.
wait()
wait() is defined in Object class. It causes the current thread to wait until another thread calls notify() or notifyAll() on the same object’s monitor.
synchronized(obj) {
obj.wait(); // releases lock and waits
}
Key Point: Releases the lock while waiting.
sleep()
sleep() is defined in Thread class. It pauses the current thread for a specified time but does not release any locks.
Thread.sleep(1000); // sleeps for 1 second
Key Point: Does not release the lock.
join()
join() is defined in Thread class. It makes the current thread wait until the thread on which join() was called finishes execution.
Thread t = new Thread(() -> {
System.out.println("Task running...");
});
t.start();
t.join(); // main thread waits until t finishes
Key Point: Used to ensure one thread completes before another continues.
Comparison Table
| Aspect | wait() | sleep() | join() |
|---|---|---|---|
| Defined In | Object class | Thread class | Thread class |
| Lock Behavior | Releases lock | Keeps lock | Keeps lock |
| Purpose | Wait for notify/notifyAll | Pause execution for time | Wait for another thread to finish |
| Throws InterruptedException | Yes | Yes | Yes |
| Common Use Case | Inter-thread communication | Delays, throttling | Thread sequencing |
Interview-Ready Notes
- wait(): Releases lock, waits for notify. Used in producer-consumer problems.
- sleep(): Pauses thread without releasing lock. Used for delays.
- join(): Ensures one thread completes before another continues. Used for sequencing.
- Common Trap: Many confuse wait() with sleep(). Clarify that wait() releases lock, sleep() does not.
Conclusion
Although wait(), sleep(), and join() all pause thread execution, their purposes differ.
wait() is for inter-thread communication, sleep() for timed pauses, and join() for sequencing threads.
In interviews, emphasize lock behavior and use cases to demonstrate deep understanding.