用于广播的Java并发队列? [英] Java concurrent queue for broadcast?

查看:126
本文介绍了用于广播的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并发队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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