A Deep Dive into the Comparison Between Sleep and Wait

Time: Column:Backend & Servers views:226

In this article, we analyze the differences between sleep and wait. sleep is 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:

  1. Pauses the current thread: The sleep method pauses the currently executing thread for a specified time, and the thread resumes after the time elapses.

  2. Does not release the lock: Even if the thread is in a sleep state and holds a lock, it does not release the lock. It still occupies the lock, preventing other threads from obtaining it.

  3. Thread state transition: The sleep method transitions the thread from the RUNNING state to the TIMED_WAITING state.

  4. Static method: It is a static method of the Thread class and is accessed using Thread.sleep.

Application Scenarios:

  1. Rate limiting: Control the execution frequency of tasks to prevent threads from overloading CPU resources.

  2. 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:

  1. Releases the lock and waits for notification: The wait method causes the current thread to wait until another thread calls the notify or notifyAll methods on the same object. When wait is called, the thread releases its lock.

  2. Must be used in synchronized blocks or methods: The wait method must be called within a synchronized block or method; otherwise, it throws an IllegalMonitorStateException.

  3. Thread state transition: The wait method transitions the thread from the RUNNING state to the WAITING state.

  4. Object method: It is a method of the Object class, so any object can invoke it.

Application Scenarios:

  1. 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.

  2. 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

Featuresleepwait
Releases lockNoYes
Needs to be in a synchronized block or methodNoYes
Belongs toThread classObject class
Throws exceptionInterruptedExceptionInterruptedException (triggered the same way)
ScopeCurrent calling threadThread holding the lock
State changeBecomes TIMED_WAITINGBecomes WAITING
Typical usagePauses a thread for a certain time, used for pacing or timed operationsThread communication, Producer-Consumer model, etc.


a2929c419620a263ac1931154e494b2e9ea90d.jpg

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.