Sleep a thread until an event is attended in another thread from a different class

Afro Genius picture Afro Genius · May 8, 2010 · Viewed 17.3k times · Source

I have an application that fires 2 threads, the 1st launches another class to do some processing which in turn launches a 3rd class to do yet more processing. The 2nd thread in the main class should wait until some event in the 3rd class completes before it performs its job. How can this be achieved?

I had tried implementing a wait/notify to share a lock object between the two threads but technically this will not work as I found the hard way. Can I share a lock between classes? Note, an instance of the 3rd class is declared in the 1st class and passed as parameter to the 2nd class. Also I tried creating boolean value in 3rd class that tells when event is complete then poll 2nd thread till this value is true. This worked but is not very desirable. Also is actionListner a better approach to this problem?

Answer

rsp picture rsp · May 8, 2010

What problem did you encounter? As you describe it, it should work. For instance you could implement 2 methods on the 3rd class which keep a flag which is checked from the one and set from the other class using the instance as lock:

boolean done = false;

public synchronized setDone() {

    done = true;

    this.notifyAll();
}

public synchronized waitUntilDone() {

     while (!done) {

        try {
             this.wait();

        } catch (InterruptedException ignore) {
             // log.debug("interrupted: " + ignore.getMessage());
        }
     }
}

(note: typed from memory, not checked using a Java compile)

In principle the this. before the wait and notifyAll is not needed, I find it clearer to include them in this situation.