Share on Google+Share on Google+

Java Thread Wait,NotifyAll

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

Advertisements

Advertisement

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.