Home Tutorial Java Thread Java Thread Wait,Notify

 
 

Share on Google+Share on Google+
Java Thread Wait,Notify
Posted on: November 9, 2009 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java Thread Wait,Notify:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 9, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com