Java Thread Wait,Notify


 

Java Thread Wait,Notify

In this segment of tutorial we will learn about the wait and notify methods in Thread.Then We will create an example and use these methods.

In this segment of tutorial we will learn about the wait and notify methods in Thread.Then We will create an example and use these methods.

  • Wait and notify both are the methods of the Object class.
  • Wait makes the object to wait for the given time or till it's notified.
  • Wait method allows other thread to work by releasing its lock.
  • Both methods are called in the synchronized context(methdod,block)


Java Thread Wait & Notify Example
public class bus {
	public static void main(String[] args) throws InterruptedException {
		passenger p = new passenger();
		p.start();
		synchronized (p) {
			System.out.println("passenger is waiting for the bus ");
			p.wait();
			System.out.println("passenger  got notification");
		}
		System.out.println("after "+p.total+" time");
	}
}

class passenger  extends Thread {
	int total = 0;

	public void run() {
		synchronized (this) { 
			System.out.println("wait .... ");
			for (int i = 0; i <= 1000; i++)
				total = total + i;
			System.out.println("passenger  is given  notification call");
			notify();
		}
	}
} 

Output :

passenger is waiting for the bus wait .... passenger is given notification call passenger got notification after 500500 time

Ads