如何确保所有生成的线程都已完成,以便继续处理?

时间:2021-07-25 20:05:14

I have a ConcurrentMap and I put elements from an ArrayList to the map for other threads to process. Once a thread finishes its processing it adds the result in the ConcurrentMap and calls a method in order for let's say the "main" thread to get and process all the results (from both the ConcurrentMap and the ArrayList).
This approach works but has a result to call the method as many times as the number of elements in the list.
Question: What constructs can I use so that the method is called once, after the ConcurrentMap is fully populated by the results of all background threads?

我有一个ConcurrentMap,我将ArrayList中的元素放到地图上,供其他线程处理。一旦线程完成其处理,它就会在ConcurrentMap中添加结果并调用一个方法,让我们说“主”线程来获取并处理所有结果(来自ConcurrentMap和ArrayList)。这种方法有效,但结果是调用方法的次数与列表中的元素数一样多。问题:在ConcurrentMap完全填充所有后台线程的结果之后,我可以使用哪些构造来调用方法一次?

2 个解决方案

#1


1  

You can use CountDownLatch initialize it with total items in Arraylist and every time a item in process count it down using countDown method,

您可以使用CountDownLatch将其初始化为Arraylist中的总项目,并且每当正在处理的项目使用countDown方法对其进行计数时,

Main thread can call await method on latch, await blocks the thread till counter reaches zero.

主线程可以在锁存器上调用await方法,等待阻塞线程直到计数器达到零。

#2


0  

In Java 8 you can do this

在Java 8中,您可以执行此操作

ConcurrentMap<Key, Value> map = ...
listToProcess.parallelStream().forEach(e -> addElementToMap(e, map));

This will perform the processing of all the element using all the CPUs you have and only return when they are all done.

这将使用您拥有的所有CPU执行所有元素的处理,并且只有在完成后才返回。

#1


1  

You can use CountDownLatch initialize it with total items in Arraylist and every time a item in process count it down using countDown method,

您可以使用CountDownLatch将其初始化为Arraylist中的总项目,并且每当正在处理的项目使用countDown方法对其进行计数时,

Main thread can call await method on latch, await blocks the thread till counter reaches zero.

主线程可以在锁存器上调用await方法,等待阻塞线程直到计数器达到零。

#2


0  

In Java 8 you can do this

在Java 8中,您可以执行此操作

ConcurrentMap<Key, Value> map = ...
listToProcess.parallelStream().forEach(e -> addElementToMap(e, map));

This will perform the processing of all the element using all the CPUs you have and only return when they are all done.

这将使用您拥有的所有CPU执行所有元素的处理,并且只有在完成后才返回。