Mor*_*gel 2 java parallel-processing java-8 java-stream
我有一个方法:
invokList(List<Object> list);
Run Code Online (Sandbox Code Playgroud)
此方法在jar中,我无法访问它的源代码。因此,我需要以并行方式执行invokList,有人可以为此提供帮助吗?
想法是将列表拆分为多个列表,然后并行执行invokList。
我做了这个例子:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
list.parallelStream()
.map(Collections::singletonList)
.forEach(Test::invokList);
}
public static void invokList(List<Integer> list) {
try {
Thread.sleep(100);
System.out.println("The Thread :" + Thread.currentThread().getName() + " is processing this list" + list);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Guava has methods Lists.partition and Iterables.partition that do something like what you're asking. Say you have a large List and want to process it in chunks of 5, you could do:
int batchSize = 5;
Lists.partition(list, batchSize)
.parallelStream()
.forEach(batch -> invokeList(batch));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
344 次 |
最近记录: |