简体   繁体   English

Java消费者线程等待所有生产者线程完成

[英]Java consumer thread to wait for all producer threads to finish

I have a multithreading task with producer-consumer pattern.我有一个生产者-消费者模式的多线程任务。 There could be many producers and one consumer.可能有许多生产者和一个消费者。 I use ArrayBlockingQueue as a shared resource.我使用 ArrayBlockingQueue 作为共享资源。

run() method in Producer class: Producer 类中的 run() 方法:

public void run() {
         for (Order order : orderList) {
             try {
                 queue.put(order);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         log.info("{} has placed all orders", Thread.currentThread().getName());
     }

run() method in Consumer class: Consumer 类中的 run() 方法:

     public void run() {
         while (!queue.isEmpty()) {
             try {
                 Order order = queue.take();
                 checkOrder(order);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         log.info("All orders has been checked");
     }

main() method: main() 方法:

// creating N producers
         for (int i = 0; i < PRODUCERS_NUM; i++) {
             Producer producer = new Producer(orderQueue, orderList);
             new Thread(producer , "Producer " + i).start();
         }
 
         Thread consumerThread = new Thread(new Consumer(orderQueue, limitList), "Consumer");
         consumerThread.start();
         consumerThread.join();

**Printing results **

Now I have consumer ending condition when queue is empty.现在,当队列为空时,我有消费者结束条件。 But there could be a moment when queue becomes empty for a moment, but some producer threads are still working.但是可能有一段时间队列变空了,但一些生产者线程仍在工作。 So I need to finish consumer thread only AFTER ALL producer threads are finished (but their count is not known beforehand).所以我只需要在所有生产者线程完成后才需要完成消费者线程(但它们的数量事先未知)。

What is the proper way to code it?编码它的正确方法是什么?

As you have a fixed number of producers, I would recommend setting a counter at the start with the number of producers.由于您有固定数量的生产者,我建议在开始时设置一个包含生产者数量的计数器。 Each producer decrements the counter when it is finished and the consumer only terminates when it reaches zero.每个生产者在完成时递减计数器,而消费者仅在达到零时终止。 For the counter, you would want to use an Atomic Integer .对于计数器,您需要使用Atomic Integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM