当生产者和消费者模式有多个消费者时面临问题;我打算创建单个生产者,将数据传递给消费者(作为Workers),这些消费者使用数据对象来处理一些人员。但问题是我不知道如何将数据传递给生产者;
让我们说我们有从某个地方获取数据的主要功能:
public function Foo(){
dataobject = new DataObject();
Sting data = dataobject.get();
}
然后将此数据传递给Queue并处理它,最终的函数应如下所示:
public function Foo(){
QueueService queue = new QueueService();
dataObject = new DataObject();
Sting data = dataobject.get();
queue.send(data);
}
我的情况如下:
Producer -> Queue <- Consumer_1, Consumer_n;
我没有使用Blocking Queue,而是使用了ThreadPool,并且遇到了我不知道如何将数据传递给消费者的问题。
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService service = null;
String threadName = Thread.currentThread().getName();
try {
service = Executors.newFixedThreadPool(6); // +1 thread for producer
service.submit(new Producer(service)).get(); // Wait until producer exits
} finally {
if (null != service) {
service.shutdown();
try {
service.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
//handle
}
}
}
System.out.println("Exit");
}
多数民众赞成好,我们生成了几个线程并开始使用它们。即使使用Worker也没有问题,这里是实现:
class Worker implements Runnable {
private String message;
public Worker(String message) {
this.message = message;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
ThreadLocalRandom random = ThreadLocalRandom.current();
try {
//Do staff
} catch (InterruptedException e) {
//handle
}
}
}
最后 - 制片人
class Producer implements Runnable {
private ExecutorService service;
Producer(ExecutorService service) {
this.service = service;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
try {
service.submit(new Worker(input));
} catch (IOException e) {
//handle
}
System.out.printf("[%s] Producer shutdown", threadName);
}
}
正如我之前提到的,我不知道如何将数据传递给制作人,我也看到了两个可能的问题: