When can we call wait() and wait(long) methods of a Thread in Java?


Whenever the wait() method is called on an object, it causes the current thread to wait until another thread invokes the notify() or notifyAll() method for this object whereas wait(long timeout) causes the current thread to wait until either another thread invokes the notify() or notifyAll() methods for this object, or a specified timeout time has elapsed.

wait()

In the below program, When wait() is called on an object, the thread enters from running to waiting state. It waits for some other thread to call notify() or notifyAll() so that it can enter runnable state, a deadlock will be formed.

Example

class MyRunnable implements Runnable {
   public void run() {
      synchronized(this) {
         System.out.println("In run() method");
         try {
            this.wait();
            System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
         } catch (InterruptedException ie) {
            ie.printStackTrace();
         }
      }
   }
}
public class WaitMethodWithoutParameterTest {
   public static void main(String[] args) {
       MyRunnable myRunnable = new MyRunnable();
       Thread thread = new Thread(myRunnable, "Thread-1");
       thread.start();
   }
}

Output

In run() method

wait(long)

In the below program, When wait(1000) is called on an object, the thread enters from running to waiting state, even if notify() or notifyAll() is not called after timeout time has elapsed thread will go from waiting to runnable state.

Example

class MyRunnable implements Runnable {
   public void run() {
      synchronized(this) {
         System.out.println("In run() method");
         try {
            this.wait(1000); 
            System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()");
         } catch (InterruptedException ie) {
            ie.printStackTrace();
         }
      }
   }
}
public class WaitMethodWithParameterTest {
   public static void main(String[] args) {
      MyRunnable myRunnable = new MyRunnable();
      Thread thread = new Thread(myRunnable, "Thread-1");
      thread.start();
   }
}

Output

In run() method
Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()

Updated on: 22-Nov-2023

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements