Difference between sleep() and wait() in Java

1. Introduction

In Java, managing the execution of threads is crucial for multi-threaded applications. The sleep() and wait() mechanisms can pause the execution of threads, but they are used in different scenarios.

The sleep() method pauses the thread for a specific period of time. On the other hand, wait() 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

Understanding the differences between sleep() and wait() is crucial for properly managing threads in Java, especially in synchronization and inter-thread communication.

sleep() wait()
Part of the Thread class. Part of the Object class.
Causes the currently executing thread to sleep (temporarily cease execution) for a specified period of milliseconds. Causes the current thread to wait until another thread invokes notify() or notifyAll() on the same object.
Do not release any locks or monitors that the thread might hold. Releases the monitor (lock) held by the thread on the object it's waiting on, allowing other threads to execute synchronized code blocks or methods on that object.
Mainly used to pause the execution of the thread for a specific time. It is mainly used for thread communication in a synchronized context to indicate that a thread is waiting for some condition to change.
Does not need to be called within a synchronized block or method. It must be called within a synchronized block or method to keep synchronization consistent and avoid IllegalMonitorStateException.
It can be interrupted, throwing an InterruptedException, which needs to be handled. It can also be interrupted, throwing an InterruptedException, and must be called in a try-catch block or declared the exception.
Useful for adding a delay or pausing the execution. Useful for managing inter-thread communication and synchronization.

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() to pause the execution of the current thread for a specified period without releasing any locks.

Use wait() when you need a thread to pause its execution until a condition is met and another thread notifies it, typically in a producer-consumer scenario.

Comments