Explain wait() and sleep() method in Java

Explain wait() and sleep() method in Java

In Java multithreading, both the wait() and sleep() methods are used to pause the execution of a thread, but they serve different purposes and behave differently:

wait() and sleep()

Explanation

1. wait() Method

  • The wait() method is used to temporarily suspend the execution of a thread and relinquish the monitor lock associated with the object on which it is called.
  • It is typically used for inter-thread communication, where one thread waits for a specific condition to be met before proceeding.
  • The wait() method must be called from within a synchronized block or method, and it releases the lock on the object until it is notified or interrupted.

2. sleep() Method

  • The sleep() method is used to temporarily suspend the execution of a thread for a specified amount of time.
  • It does not release any locks held by the thread and does not require synchronization.
  • The sleep() method is often used for delaying the execution of a thread or for introducing pauses in a program’s execution.

Example
java
public class WaitSleepExample {
    public static void main(String[] args) {
        Object lock = new Object();

        Thread waitThread = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("Wait thread is waiting...");
                    lock.wait(); // Wait indefinitely until notified
                    System.out.println("Wait thread has been notified and resumed");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread sleepThread = new Thread(() -> {
            try {
                System.out.println("Sleep thread is sleeping...");
                Thread.sleep(3000); // Sleep for 3 seconds
                System.out.println("Sleep thread has woken up");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        waitThread.start();
        sleepThread.start();

        // Notify the wait thread after 2 seconds
        try {
            Thread.sleep(2000);
            synchronized (lock) {
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In this example, we have two threads: waitThread and sleepThread. The waitThread uses the wait() method to wait indefinitely until it is notified by another thread. On the other hand, the sleepThread uses the sleep() method to sleep for 3 seconds before continuing its execution. The main thread notifies the waitThread after 2 seconds using the notify() method, which wakes up the waitThread from its wait state. This example demonstrates the differences between wait() and sleep() in terms of their usage and behavior.

Homepage

Readmore