Jim Hoglund wrote:Rahul : Here is a modified version of your code. The main thing to notice is that both threads synchronize on the same instance of a lock object. Also since the threads have to wait on each other, each must wait() and each must notify(). The Operator instance, when notified, does its work only if ready is false. Similarly, Machine, when notified, fires up to work only if ready is true. This is the common wait/notify construct; placed in code synchronized on the same object; checking and changing a condition flag.
Jim ... ...
Rahul Nair wrote:
I understand the changes i need to do.
The things we have to keep in mind for thread communication is that:
1. Both threads have to acquire lock on same instance.
2. Both threads have to wait for each others work to complete.
Jim Hoglund wrote:
Henry : A bit more on the technical stuff. The while() loop models the business process and
I let it do double duty knowing that Operator won't get the lock unless the condition is false.
But as you point out, this defeats the purpose of the condition flag. I used notifyAll() just
to allow for multiple listeners. [Note to self; must wait() while(condition) not if(condition).]
Jim Hoglund wrote:My understanding is that if you have multiple waiting threads, each looking for
a different condition, and you use notify(), the one thread you wake up may not
be interested in the current condition; the notify() will be wasted. So you must
use notifyAll() to be sure the desired thread will run. Am I missing something?