W3docs

Difference between "wait()" vs "sleep()" in Java

In Java, the wait() method is used to pause the current thread and allow other threads to execute. It is called on an object and causes the current thread to wait until another thread calls the notify() or notifyAll() method on the same object.

In Java, the wait() method is used to pause the current thread and allow other threads to execute. It is called on an object and causes the current thread to wait until another thread calls the notify() or notifyAll() method on the same object.

The sleep() method, on the other hand, is a static method that causes the current thread to pause for a specific amount of time. It is called on the Thread class, does not require object synchronization, and does not release any held object locks.

Here are a few key differences between wait() and sleep():

  • wait() is used for inter-thread communication, while sleep() is used to introduce a delay.
  • wait() releases the lock on an object while it is waiting, while sleep() does not.
  • Both wait() and sleep() can be interrupted and throw InterruptedException.

Here's an example of using wait() and notify() for inter-thread communication:


class SharedMonitor {
    public synchronized void doNotify() {
        notify();
    }
    public synchronized void doWait() {
        while (/* condition */) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

And here's an example of using sleep() to introduce a delay:


class MyThread extends Thread {
    public void run() {
        try {
            Thread.sleep(1000); // pause for 1 second
            // do something
        } catch (InterruptedException e) {
            // handle exception
        }
    }
}