Home Tutorial Java Thread Java Thread Wait,NotifyAll

 
 

Java Thread Wait,NotifyAll
Posted on: November 9, 2009 at 12:00 AM
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

Related Tags for Java Thread Wait,NotifyAll:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.