我有多个BlockingQueues,其中包含要发送的消息。消费者数量可能少于队列数量吗?我不想遍历队列并继续轮询它们(忙于等待),也不想为每个队列都分配一个线程。相反,当消息在任何队列上可用时,我希望唤醒一个线程。
I have multiple BlockingQueues containing messages to be sent. Is it possible to have fewer consumers than queues? I don't want to loop over the queues and keep polling them (busy waiting) and I don't want a thread for every queue. Instead, I would like to have one thread that is awoken when a message is available on any of the queues.
推荐答案一个窍门你可以做的就是排一个队列。因此,您要做的是只有一个阻塞队列,所有线程都订阅该队列。然后,当您将某些内容排队到其中一个BlockingQueues中时,您还将排队队列也排队到了该单个队列中。因此,您将遇到以下情况:
One trick that you could do is to have a queue of queues. So what you'd do is have a single blocking queue which all threads subscribe to. Then when you enqueue something into one of your BlockingQueues, you also enqueue your blocking queue on this single queue. So you would have something like:
BlockingQueue<WorkItem> producers[] = new BlockingQueue<WorkItem>[NUM_PRODUCERS]; BlockingQueue<BlockingQueue<WorkItem>> producerProducer = new BlockingQueue<BlockingQueue<WorkItem>>();然后,当您获得新的工作项目时:
Then when you get a new work item:
void addWorkItem(int queueIndex, WorkItem workItem) { assert queueIndex >= 0 && queueIndex < NUM_PRODUCERS : "Pick a valid number"; //Note: You may want to make the two operations a single atomic operation producers[queueIndex].add(workItem); producerProducer.add(producers[queueIndex]); }现在,您的所有消费者都可以在ProducerProducer上进行封锁了。我不确定该策略的价值如何,但是它确实可以实现您想要的功能。
Now your consumers can all block on the producerProducer. I am not sure how valuable this strategy would be, but it does accomplish what you want.
更多推荐
多个阻止队列,单个使用者
发布评论