wait() notify() and notifyAll() method in Java

In this post, we will see wait() notify() and notifyAll() methods in java  These methods have been defined in the object class. Let’s see some points related to the wait() method.

wait() notify() and notifyAll() method in Java

  • Method declaration – There are three overloaded versions has been defined for wait() method and all throws checked exception i.e InterruptedException while using wait() method we need to use try/catch or throws keyword.

public final void wait() throws InterruptedException
public final native void wait(long timeout) throws InterruptedException.
public final void wait(long timeout, int nanos) throws InterruptedException

  • What is does – Calling wait() method results, current thread to wait until some other thread calls notify() or notifyAll() on the same object.
  • The wait() method must be called in synchronized context.

 

package multithreading;

class Thread1 extends Thread {

	@Override
	public void run() {

		System.out.println("before wait() method");
		synchronized (this) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("inside synchronized block after wait() method");
		}

	}
}

public class ThreadExampleWaitMethod {

	public static void main(String[] args) {
		Thread1 thread1 = new Thread1();
		thread1.start();
	}
}

 

Output is – before wait() method

Did you notice synchronized block’s  System.out.println(line number 15) didn’t execute, because we didn’t provide wait time. If we pass some wait time then line 15 will execute.

In below example we will provide wait time 1000 mili sec.


package multithreading;

class Thread1 extends Thread {

	@Override
	public void run() {

		System.out.println("before wait() method");
		synchronized (this) {
			try {
				wait(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("inside synchronized block after wait() method");
		}

	}
}

public class ThreadExampleWaitMethod {

	public static void main(String[] args) {
		Thread1 thread1 = new Thread1();
		thread1.start();
	}
}

Output is –

before wait() method
inside synchronized block after wait() method

notify() method in java – Wakes up a single thread that is waiting on this object’s monitor.

notifyAll() method in java – Wakes up all threads that are waiting on this object’s monitor.


That’s all about wait() notify() and notifyAll() method in Java.

You may like.

Object class where these method has been defined.