Hi Jennifer,
I had a couple of thoughts.
On making sure your drinker and filler are using the same glass object.
~~~~~~~~~~~~~~~~`
One way is to instantiate your Glass object before you instantiate your drinker and filler objects. Then, when you instantiate your drinker and filler, make sure their constructor can receive a reference to your previously instantiated Glass object. That way, they'll both be trying to access the same Glass object.
As for the relationship between drink and fill, I've been known to become confused on this question, but I think that the following logic is correct.
drink() and refill()
~~~~~~~~~~~~~~~~~~~~
If you use a while loop rather than an if statement, the glass will be constantly aware of it's state, and better able to inform all waiting threads through notifyAll() as soon as it's state changes.
I'd put the wait() statement within the while loop (inside a try/catch block for interruptedException catching), and a notifyAll() statement outside the loop.
eg. while loop in the drink method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
while the glass is empty
......tell the requesting
thread to wait()
Following while (outside the while loop),
......notifyAll()
......change the state to reflect an empty glass
eg. while loop in the refill method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
while the glass is full
......tell the requesting thread to wait()
Following while (outside the while loop),
......notifyAll()
......change the state to reflect a full glass
That way, when the condition in while changes, control will fall through the while loop, and the notifyAll statement will execute. Any waiting threads will then get a chance to again try to gain access to whichever method they wanted.
cheerio
rowan
Originally posted by Jennifer Wallace:
[B]Hi,
I was trying to code a simple example to understand the concept of wait and notify. I got stuck when I tried to code it.
There is a Glass Object which could be emptied and refilled.
There are two persons(Threads) doing it - one the emptying and the other refilling. They have to wait and notify each other if the desired state of the glass is not yet reached.