On below code, notifyAll() won't alter anything in the program execution. In my understanding , the wait() condition will wait on the t1 thread to finish (complete the run() method) and then continue.
In this case, with or without the notifyAll() the execution will be the same. Could someone clarify the difference in using it or not?
I'm using Java 8.
public class ThreadsTest {
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread t1 = new Thread(thread1, "t1");
t1.start();
synchronized (t1) {
System.out.println("Waiting for t1 to complete");
t1.wait();
System.out.println("Thread t1 finished, result = " + thread1.total);
}
}
}
class Thread1 implements Runnable {
int total;
@Override
public void run() {
synchronized (this) {
for (int i=0 ; i<100; i++) {
total++;
// Below line won't alter anything in program execution
//notifyAll();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Output in both cases will be:
waiting for t1 to complete
t1 finished, result = 100