While studying the SCJP I typed out a lot of the threading code because my brain doesn't process long code dumps very well. This code is taken from the Sanghera book, and is supposed to be a trivial example of wait/notify.
The output is supposed to be:
Which it is, 99%+ of the time. The thing is if I keep running it, eventually I will get this:
Thought it would be a good exercise to try to fix this, but I'm stumped and don't see the problem with the original code. Any help?
The problem is that the wrong target is awoken with the notify() method call.
For this code to work, the consumer *must* wake up the producer on notify() call. Since the consumers are being started, which takes some time, there is a good chance for this (since the consumer may not be waiting yet). However, if the consumer wakes up another consumer instead, the notification is just ignored as the consumer just goes back into a wait state -- and then, there will be nothing to wake up the producer.