本文介绍了Java:LinkedBlockingQueue是否考虑到消费者的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个主题:2个消费者, ConsumerA ConsumerB

I have 3 threads: 2 consumers, ConsumerA and ConsumerB, and a Producer.

我也有一个 LinkedBlockingQueue队列

在t = 1时: ConsumerA 调用queue.take()

At t=1: ConsumerA calls queue.take()

2:消费者 B调用queue.take()

At t=2: ConsumerB calls queue.take()

在t = 3时: 调用queue.put(foo)

At t=3: Producer calls queue.put(foo)

是否保证ConsumerA在ConsumerB之前接收foo?换句话说,消费者调用 take()的顺序是每个通知的顺序?

Is it guaranteed that ConsumerA receives foo before ConsumerB? In other words, the order in which the consumers invokes take() is the order in which each is notified?

推荐答案

从查看源代码时可以看出, ,它不能保证。根据调度程序的感觉,随机唤醒一个线程,有一个警戒块机制。

From looking at the source code, it's not guaranteed. There's a guarded block mechanism in place with the waking up of one thread at random, depending on how the scheduler feels.

 notEmpty.signal(); // propagate to a non-interrupted thread

完整代码:

编辑:再次看到ReenterantLock和Condition,线程以FIFO顺序发出信号,显然。因此,第一个线程等待插入将首先发出信号。但是,这些都是实现细节!不要依赖它们。

just looked again at ReenterantLock and Condition, the threads are signalled in FIFO order, apparently. So, the first thread to wait for insertion will be signalled first. However, these are implementation details! Do not rely on them.

这篇关于Java:LinkedBlockingQueue是否考虑到消费者的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:50