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?
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.