简体   繁体   中英

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.

run() method in Producer class:

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:

     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:

// 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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