I have 3 threads: 2 consumers, ConsumerA and ConsumerB, and a Producer.
I also have a LinkedBlockingQueue queue
At t=1: ConsumerA calls queue.take()
At t=2: ConsumerB calls queue.take()
At t=3: Producer calls queue.put(foo)
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?
If not, is there an alternative data structure that will give higher priority based on order?
解决方案
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
Edit: 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.
an implementation is not required to
define exactly the same guarantees or
semantics for all three forms of
waiting, nor is it required to support
interruption of the actual suspension
of the thread