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.

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 and does not require any object synchronization.

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.
  • wait() can be interrupted, while sleep() cannot.

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

class ThreadA {
  public void run() {
    synchronized(this) {
      // do something
      notify();
    }
  }
}

class ThreadB {
  public void run() {
    synchronized(this) {
      wait();
      // do something
    }
  }
}

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
    }
  }
}