1. Introduction
In Java, managing the execution of threads is crucial for multi-threaded applications. sleep() and wait() are two mechanisms that can pause the execution of threads, but they are used in different scenarios. sleep() is a method that pauses the thread for a specific period of time. On the other hand, wait() is a method that pauses a thread until it's notified, typically by another thread.
2. Key Points
1. sleep() is a static method that belongs to the Thread class and does not release the monitor.
2. wait() is a method of the Object class that releases the monitor and must be called from a synchronized context.
3. sleep() keeps the lock for the duration of the sleep.
4. wait() releases the lock immediately for other objects to acquire.
5. A thread resumes execution from sleep() once the specified time period is over.
6. A thread resumes from wait() when notify() or notifyAll() is called on the object it's waiting on.
3. Differences
sleep() | wait() |
---|---|
Does not release the lock. | Releases the lock. |
Belongs to the Thread class. | Belongs to an Object class. |
Pauses the thread for a specified time. | Pauses the thread until it's notified. |
4. Example
public class SleepAndWait {
private static final Object LOCK = new Object();
public static void main(String[] args) throws InterruptedException {
Thread sleepThread = new Thread(() -> {
try {
// Step 1: The thread sleeps for 2000 milliseconds
System.out.println("Sleeping thread is going to sleep.");
Thread.sleep(2000);
System.out.println("Sleeping thread woke up.");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread waitThread = new Thread(() -> {
synchronized (LOCK) {
try {
// Step 2: The thread waits until it gets notified
System.out.println("Waiting thread is going to wait.");
LOCK.wait();
System.out.println("Waiting thread got notified.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
sleepThread.start();
waitThread.start();
// Ensuring the waiting thread goes on wait
Thread.sleep(500);
synchronized (LOCK) {
// Step 3: Notifying the waiting thread
LOCK.notify();
}
}
}
Output:
Sleeping thread is going to sleep. Waiting thread is going to wait. Waiting thread got notified. Sleeping thread woke up.
Explanation:
1. sleepThread calls sleep() causing it to sleep for 2 seconds regardless of any other operations.
2. waitThread calls wait() within a synchronized block, releasing the lock on LOCK and waiting to be notified.
3. The main thread sleeps for half a second to ensure waitThread gets to wait().
4. The main thread then synchronizes on LOCK and calls notify(), which wakes up waitThread.
5. When to use?
- Use sleep() when you want to pause the execution of the current thread for a specified period without releasing any locks.
- Use wait() when you need to have a thread pause its execution until some condition is met and it's notified by another thread, typically in a producer-consumer scenario.
Comments
Post a Comment
Leave Comment