我正在研究 Java 的生产者-消费者问题的多个生产者和消费者用例。代码在github上。相同的实现适用于单个生产者消费者用例,但对于多个生产者消费者用例表现得很奇怪。
我对输出有一些疑问:
一开始,所有生产者和一个消费者都拥有锁:
Producer t1 has lock
t5 produced 1, integerQueue: [1]
Producer t5 notifiedAll
我认为所有线程都应该竞争锁,并且应该最多有一个线程一直拥有锁?所有生产者都共享锁吗?当生产者线程 t1 持有锁时,消费者线程 t5 如何获得锁?
运行一段时间后,又出现了一个奇怪的现象:
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
似乎除了一个生产者和消费者之外的所有线程都已死亡,并且这两个线程正在彼此之间切换锁。为什么会发生这种情况?所有其他生产者和消费者发生了什么?
任何帮助是极大的赞赏。
慕后森
相关分类