1

I'm new to Java multithreading and written a small program to test how the wait() and notifyAll() methods interact with each other. But why doesn't this program work?

package sample;
    
    public class Main {
    
        public static void main(String[] args) {
            new Thread(new MyWriter()).start();
            new Thread(new MyReader()).start();
        }
    }
    
    class MyReader implements Runnable {
    
        @Override
        public synchronized void run() {
            while(true) {
                notifyAll();
            }
        }
    }
    
    class MyWriter implements Runnable {
    
        @Override
        public synchronized void run() {
            while(true) {
                try {
           

     System.out.println("Waiting...");
                wait();
                System.out.println("Wait Terminated");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

When running, I expected the output to be

Waiting...
Wait Terminated

But it outputs

Waiting...

And just waits forever until I terminate it manually.

  • 1
    You need to wait/notify on a common object. You could simply create an instance of `Object` and pass it to both threads – MadProgrammer Feb 27 '22 at 23:01

1 Answers1

3

A notify call notifies the objects waiting on the monitor of an object. So, if you issue wait on an object, you have to notify using the same object.

One way to do this is to simply use a shared object:

public static void main(String[] args) {
     Object lock=new Object();
     new Thread(new MyWriter(lock)).start();
     new Thread(new MyReader(lock)).start();
}

Then:

public void run() {
 while(true) {
    synchronized(lock) {
        lock.notifyAll();
    }
 }

public void run() {
   while(true) {
      try {
         synchronized(lock) {        
             System.out.println("Waiting...");
             lock.wait();
             System.out.println("Wait Terminated");
         }
      } ...
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59