The issue arises because both TrainA and TrainB are independently looping over the size of a shared ConcurrentLinkedDeque
, and since TrainA
frequently gets scheduled first, it removes all elements from the queue before TrainB
can access them. This results in TrainB
repeatedly seeing an empty queue and doing nothing. Additionally, the use of a for
loop with station.getQueue().size()
is not thread-safe in a concurrent context, as the queue size can change dynamically during iteration. To resolve this, you should consider replacing the ConcurrentLinkedDeque
with a thread-safe BlockingQueue
such as LinkedBlockingQueue
, which naturally handles concurrent producer-consumer scenarios. This ensures that both trains block and wait when the queue is empty, leading to more balanced consumption of passengers by both TrainA and TrainB.