Home Tutorial Java Thread Java Thread Wait,NotifyAll

 
 

Share on Google+Share on Google+
Java Thread Wait,NotifyAll
Posted on: November 9, 2009 at 12:00 AM
Advertisement
In this segment of tutorial we will learn about the wait and notifyAll methods of the Thread.Then We will create an example which is notifying all the threads at a time.

  • Wait notifyAll both are the methods of the object class.
  • notify is used to notify only the first waiting thread.
  • notifyAll notifies all the thread to resume their lock


Java Thread Wait Notifyall Example
class passenger extends Thread {
	train tr;

	public passenger(train trn) {
		tr = trn;
	}

	public void run() {
		synchronized (tr) {
			try {
				System.out.println("Waiting for train...");
				tr.wait();
			} catch (InterruptedException e) {
			}
			System.out.println("Total is: " + tr.total);
		}
	}

	public static void main(String[] args) {
		train mytrain = new train();
		new passenger(mytrain).start();
		new passenger(mytrain).start();
		new passenger(mytrain).start();
		mytrain.start();
	}
}

class train extends Thread {
	int total;

	public void run() {
		synchronized (this) {
			for (int i = 0; i < 100; i++) {
				total += i;
			}
			notifyAll();
		}
	}
}

Output

Waiting for train... Waiting for train... Waiting for train... Total is: 4950 Total is: 4950 Total is: 4950
Advertisement

Related Tags for Java Thread Wait,NotifyAll:


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