[英]How can I make sure that all the spawned threads are done so that processing can continue?
I have a ConcurrentMap
and I put elements from an ArrayList
to the map for other threads to process. 我有一个
ConcurrentMap
,我将ArrayList
中的元素放到地图ArrayList
其他线程处理。 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
). 线程完成处理后,将结果添加到
ConcurrentMap
并调用一个方法,以便让“主”线程获取并处理所有结果(来自ConcurrentMap
和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
之后,我可以使用哪种构造以便一次调用该方法?
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
方法对其进行countDown
计数时,
Main thread can call await
method on latch, await blocks the thread till counter reaches zero. 主线程可以在闩锁上调用
await
方法,await阻塞线程,直到计数器达到零为止。
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执行所有元素的处理,并且仅在完成所有处理后才返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.