多个阻止队列,单个使用者

编程入门 行业动态 更新时间:2024-10-24 20:22:55
本文介绍了多个阻止队列,单个使用者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

多个阻止队列,单个使用者

本文发布于:2023-10-15 00:55:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492761.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   队列   使用者

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!