I'm working on the multiple producer and consumer use case of Producer-Consumer problem with Java. The code is on github. The same implementation worked for the single producer consumer use case, but behaved weirdly for the multiple producer consumer case.
I have some questions regarding the output:
At the start, all producers and one consumer has the lock:
Producer t1 has lock
t5 produced 1, integerQueue: [1]
Producer t5 notifiedAll
- I thought all threads should compete for the lock and there should be at most one thread that has the lock of all time? Are all producers sharing the lock? How did consumer thread t5 get the lock while producer thread t1 was holding it?
After it runs for a while, another weird phenomenon appears:
Producer t5 has lock
t5 produced 10, integerQueue: [8, 9, 10]
Producer t5 notifiedAll
Producer t5 has lock
t5 produced 11, integerQueue: [8, 9, 10, 11]
Producer t5 notifiedAll
Consumer t8 has lock
t8 consumed 8, integerQueue: [9, 10, 11]
Consumer t8 notified All
Consumer t8 has lock
t8 consumed 9, integerQueue: [10, 11]
Consumer t8 notified All
- It seems all threads except one producer and consumer had died and those 2 are switching lock between each other. Why is this happening? What happened to all the other producers and consumers?
Any help is greatly appreciated.