In this article, we analyze the differences between
sleepandwait.sleepis used to pause the current thread for a specified period while retaining the lock, commonly used to control execution timing or for scheduling tasks.
In computer programming, especially in multi-threaded or concurrent environments, sleep and wait are two very common functions, but they have different purposes and mechanisms. This article will explore the differences between sleep and wait in detail, including their internal workings, application scenarios, and detailed code examples, to help fully understand their usage.
sleep
Mechanism:
Pauses the current thread: The
sleepmethod pauses the currently executing thread for a specified time, and the thread resumes after the time elapses.Does not release the lock: Even if the thread is in a
sleepstate and holds a lock, it does not release the lock. It still occupies the lock, preventing other threads from obtaining it.Thread state transition: The
sleepmethod transitions the thread from the RUNNING state to the TIMED_WAITING state.Static method: It is a static method of the
Threadclass and is accessed usingThread.sleep.
Application Scenarios:
Rate limiting: Control the execution frequency of tasks to prevent threads from overloading CPU resources.
Scheduled tasks: Execute certain tasks at intervals within a loop.
Code Example:
public class SleepExample extends Thread {
public void run() {
try {
System.out.println("Thread going to sleep for 2 seconds.");
Thread.sleep(2000); // Sleep for 2 seconds
System.out.println("Thread woke up after sleeping.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepExample thread = new SleepExample();
thread.start();
}
}wait
Mechanism:
Releases the lock and waits for notification: The
waitmethod causes the current thread to wait until another thread calls thenotifyornotifyAllmethods on the same object. Whenwaitis called, the thread releases its lock.Must be used in synchronized blocks or methods: The
waitmethod must be called within a synchronized block or method; otherwise, it throws anIllegalMonitorStateException.Thread state transition: The
waitmethod transitions the thread from the RUNNING state to the WAITING state.Object method: It is a method of the
Objectclass, so any object can invoke it.
Application Scenarios:
Thread communication: When multiple threads work together, one thread can wait for a condition to be met before being notified by another thread to continue.
Producer-Consumer model: Often used in synchronization in the producer-consumer pattern.
Code Example:
public class WaitNotifyExample {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
// Waiting thread
Thread waitingThread = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("Thread waiting for the lock to be released.");
lock.wait(); // Enters the waiting state and releases the lock
System.out.println("Thread resumed after lock released.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Notifying thread
Thread notifyingThread = new Thread(() -> {
synchronized (lock) {
System.out.println("Notifying other threads.");
lock.notify(); // Notify the waiting thread
System.out.println("Notified waiting thread.");
}
});
waitingThread.start();
Thread.sleep(1000); // Ensure waitingThread holds the lock and enters the waiting state
notifyingThread.start();
}
}Comparison between sleep and wait
| Feature | sleep | wait |
|---|---|---|
| Releases lock | No | Yes |
| Needs to be in a synchronized block or method | No | Yes |
| Belongs to | Thread class | Object class |
| Throws exception | InterruptedException | InterruptedException (triggered the same way) |
| Scope | Current calling thread | Thread holding the lock |
| State change | Becomes TIMED_WAITING | Becomes WAITING |
| Typical usage | Pauses a thread for a certain time, used for pacing or timed operations | Thread communication, Producer-Consumer model, etc. |
Summary
In this article, we analyzed sleep and wait. sleep is used to pause the current thread for a specified duration while retaining the lock, commonly for pacing or timing operations. On the other hand, wait releases the lock and puts the thread in a waiting state until it is awakened by notify or notifyAll. It must be used within synchronized blocks and is suitable for inter-thread communication, such as in the Producer-Consumer model.
