Question
What is the difference between wait() and sleep() in Java threads?
Answer
In Java, both `wait()` and `sleep()` are methods used for pausing the execution of threads. However, they serve different purposes and have distinct behaviors that are crucial for thread management. Understanding these differences can significantly enhance your thread synchronization strategies.
// Example of wait() and sleep() usage in Java
class WaitSleepExample {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
try {
// Using wait()
System.out.println("Thread 1: Waiting...");
lock.wait(); // Releases lock and goes to waiting state
System.out.println("Thread 1: Resumed!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
Thread thread2 = new Thread(() -> {
try {
// Using sleep()
Thread.sleep(2000); // Sleeps for 2 seconds without releasing lock
synchronized (lock) {
System.out.println("Thread 2: Notify after sleep");
lock.notify(); // Wakes up waiting thread
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}
Causes
- `wait()` is used for inter-thread communication and requires the thread to hold a monitor lock, relinquishing it while waiting.
- `sleep()` simply puts the thread into a non-runnable state for a specified duration without releasing any lock it holds.
Solutions
- Use `wait()` when you want a thread to wait for another thread to perform a certain action, typically when dealing with monitor objects and synchronized code blocks.
- Use `sleep()` when you want a thread to pause execution temporarily without releasing locks; it's often used for creating delays in execution.
Common Mistakes
Mistake: Confusing the purpose of wait() and sleep() leading to improper thread behavior.
Solution: Recognize that wait() is meant for inter-thread communication, while sleep() is for pausing execution.
Mistake: Failing to call wait() in a synchronized block or method causing IllegalMonitorStateException.
Solution: Always ensure that wait() is called within a synchronized context.
Helpers
- Java threads
- wait() method in Java
- sleep() method Java
- Java multithreading
- difference between wait and sleep in Java