But both are supposed to happen concurrently?
The problem here is that the production (and the consumption) take very little time. You are seeing what is called a (non critical) race condition and the producer is able to produce all 10 items before the consumer even starts. By race condition I mean that your two threads are racing each other to produce and consume, not a bug in this case.
If you increased your test to (let's say) 100000 items, you would see producing and consuming messages intermixed although even then you might see blocks of producing
and consuming
messages that were 10 or more in length.
Another thing to try would be to start the consumer first and put a Thread.sleep(10);
after you start it so that it is waiting for the producer. Then the consumer would then have time to call wait()
and would be moved from WAIT
to BLOCKED
as soon as the first notifyAll()
was called. But even then, the race condition might show all the producing
messages before the consuming
. That is the asynchronous nature of multi-threaded applications.
p.s. It is always a good pattern to properly handle InterruptedException
. You should do something like:
try {
wait(); // give up lock and wait
} catch (InterruptedException e) {
// reset the thread interrupt flag
Thread.currentThread().interrupt();
// probably stopping the thread is best
return;
}