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.
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.
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