0

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
  • In order for wait and notify to cooperate correctly you need to synchronize on the same object but in your example you have 2 distinct objects `thread1` and `t1`. Have a look at http://www.programcreek.com/2009/02/notify-and-wait-example/ and this answer http://stackoverflow.com/a/886799/1333481. – zafarkhaja Mar 31 '16 at 06:01
  • Actual possible duplicate http://stackoverflow.com/q/5121173/1333481 – zafarkhaja Mar 31 '16 at 08:07

0 Answers0