0

so I'm working on this report, and the last assignment is to create a producer/consumer model with n Producers and one Consumer, the trick is that i have to make it work with notify() instead of notifyAll() in the put and get methods.

I figure just leaving it as is in the get method isn't a problem, since there's only the one consumer, but I'm having trouble figuring out how to make sure the notify() in the put method only calls the consumer thread, instead of waking up another producer and causing deadlock.

CoderPi
  • 12,985
  • 4
  • 34
  • 62
Plissken
  • 1
  • 2
  • How _I_ would solve that problem is, I would use a `ReentrantLock` instance instead of using Java `synchronized` statements, and I would allocate _two_ condition variables; one for waking the consumer, and one for waking producers. But, if you _must_ use `Object#wait()` and `Object#notify()` then you'll have to invent some means for a producer thread to know when it returns from a `wait()` call whether the notify was intended for the producers or for the consumer. If it was intended for the consumer, then the producer thread will have to re-notify, and then go back to waiting. – Solomon Slow Nov 29 '15 at 18:04

1 Answers1

0

You can't decide who gets woken up. That's why you need additional logic so if the wrong thread is notified, it will know that it shouldn't run and notify() another thread (and re-wait() itself).

Kayaman
  • 72,141
  • 5
  • 83
  • 121