用于广播的Java并发队列?

编程入门 行业动态 更新时间:2024-10-10 23:15:33
本文介绍了用于广播的Java并发队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一堆生产者线程添加到 BlockingQueue 和一个工作线程获取对象。现在我想扩展这个,所以两个工作线程正在接受对象,但是对对象做了不同的工作。这是扭曲:我想要一个被放在队列中的对象由接收线程的 处理。

I have a bunch of producer threads adding to a BlockingQueue and one worker thread taking objects. Now I want to extend this so two worker threads are taking objects, but doing different work on the objects. Here's the twist: I want an object that has been put on the queue to be worked on by both of the receiving threads.

如果我继续使用BlockingQueue,两个线程将竞争对象,并且只有一个工作线程将获得该对象。

If I keep using BlockingQueue, the two threads will compete for the objects, and only one of the worker threads will get the object.

所以我'我正在寻找类似于BlockingQueue的东西,但有广播行为。

So I'm looking for something similar to BlockingQueue, but with broadcast behaviour.

应用程序:生产者线程实际上正在创建性能测量,其中一个工作人员正在编写测量结果一个文件,而另一个工人正在聚合统计数据。

The application: The producer threads are actually creating performance measurements, and one of the workers is writing the measurements to a file, while the other worker is aggregating statistics.

我正在使用Java 6.

I'm using Java 6.

所以这样的机制存在吗?在Java SE?别处?或者我需要自己编写代码?

So does such a mechanism exist? In Java SE? Elsewhere? Or do I need to code my own?

我正在寻找占用空间小的解决方案 - 我不想安装一些框架​​来实现这一目标。

I'm looking for solutions with a small footprint - I'd prefer not to install some framework to do this.

推荐答案

一个选项:拥有三个阻塞队列。您的主要制作人将项目放入广播队列。然后你有那个队列的消费者,它消耗每个项目,把它放到两个其他队列中,每个队列由一个消费者提供服务:

One option: have three blocking queues. Your main producer puts items into a "broadcast" queue. You then have a consumer of that queue which consumes each item, putting it into both of the other queues, each of which is serviced by a single consumer:

Q2 ---- Real Consumer 1 Q1 / Producer ---- Broadcast Consumer \ ---- Real Consumer 2 Q3

或者,你可以给两个阻止排队到制作人,然后让它把它产生的项目放到两者中。这不太优雅,但总体上稍微简单一些:)

Alternatively, you could give two blocking queues to the producer, and just get it to put the items it produces into both. That's less elegant, but slightly simpler overall :)

更多推荐

用于广播的Java并发队列?

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

发布评论

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

>www.elefans.com

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