javanetbeansconcurrency

How to use wait() and notify() with the use of different classes in Java


I am trying to enclose a wait function in classA, but I want to notify() from classB. How can I achieve this?


Solution

  • You have multiple options here. The simplest is created an object, of any type really, and sharing that object between the two classes.

    Any object in java can has the notify() and wait() methods.

    So you can create an object

    Object sharedObject = new Object();
    

    Then pass that object to both classes (or more accurately, instance of the classes)

    ClassA a = new ClassA(sharedObject);
    ClassB b = new ClassB(sharedObject);
    

    Then inside some method in ClassA you can call:

    synchronized(sharedObject) {
         sharedObject.wait();
    }
    

    On one thread, and then on another thread you can wake it up by calling:

    synchronized(sharedObject) {
         sharedObject.notify();
    }
    

    That is a basic way of doing this. Notice, that before waiting or notifying you need to synchronize on that object.

    There's a more advanced and robust way to do it, with condition variables.