Question

I'm trying to do the Unisex Bathroom problem in Java. In short, there is one bathroom with an infinite number of toilets that both men and women can use. Men and women can't be in the bathroom at the same time, but several men or women can. Men and women are represented by threads, and the bathroom by a monitor (shared object with synchronized methods, that monitors and dictates how the concurrency works).

Now to my question. Normally you would write something like:

public synchronized void womanEnter()
{
   while(menInTheBathroom>0 || menWaiting>0)
   {
      wait();
   }
    //enter bathroom
}

And to wake that process up you notify() But I (think I) need to be able to notify men and women separately. If a man enters the bathroom I want him to notify all the men in the queue. I could use a couple of semaphores in the monitor, but that's not allowed in the excersize. Can I use conditions in the monitor that I can wait for and notify, and if I can, how? I tried, but got a bunch of errors involving illegal monitor state.

Was it helpful?

Solution

You would need to use notifyAll to catch all cases (typically notify is more specific). Your while loop (don't use an if) protects against continuing in unwanted cases.

More efficiently, but also more verbosely, you could use Condition from the locks in java.util.concurrent.locks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top