多个阻止队列,单个使用者 [英] Multiple blocking queues, single consumer

查看:53
本文介绍了多个阻止队列,单个使用者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个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.

这篇关于多个阻止队列,单个使用者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆