Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the wait() method not trigger notifyAll()?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Waiting...

And just waits forever until I terminate it manually.

>Solution :

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");
         }
      } ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading