假设我们有一个列表并且想要选择满足某个属性的所有元素(比如一些函数 f)。有 3 种方法可以并行执行此过程。
一 :
listA.parallelStream.filter(element -> f(element)).collect(Collectors.toList());
二:
listA.parallelStream.collect(Collectors.partitioningBy(element -> f(element))).get(true);
三:
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
//separate the listA into several batches
for each batch {
Future<List<T>> result = executorService.submit(() -> {
// test the elements in this batch and return the validate element list
});
}
//merge the results from different threads.
假设测试功能是 CPU 密集型任务。我想知道哪种方法更有效。非常感谢。
收到一只叮咚
潇潇雨雨
相关分类