Share on Google+Share on Google+

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.

  • 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();
		synchronized (p) {
			System.out.println("passenger is waiting for the bus ");
			System.out.println("passenger  got notification");
		System.out.println("after "" 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");

Output :

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


Posted on: November 9, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null