gpt4 book ai didi

使用流和可调用对象的 Java ThreadPoolExecutor

转载 作者:行者123 更新时间:2023-11-30 06:42:13 25 4
gpt4 key购买 nike

我有一个实现 Callable 的类, 它有一个覆盖 call 的方法并返回 Long .

我创建了一个 ListCallable<Long>作为

List<Callable<Long>> callables = new ArrayList<>();
for (File fileEntry : folder.listFiles()) {
callables.add(new DataProcessor(fileEntry));

我有

ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(10);

我调用

threadPoolExecutor.invokeAll(callables)
.stream()
.map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
})
.collect(Collectors.toLong(/* what goes here? */));

我想做的是对 future.get() 的所有返回值求和.

此外,由于我正在调用 invokeAll,我还需要关闭 Executor 吗?

最佳答案

您可以使用 Stream.mapToLongfuture.get 映射为 LongStream 然后找到 sum流为:

long sum = threadPoolExecutor.invokeAll(callables)
.stream()
.mapToLong(future -> {
try {
return future.get();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}) // LongStream
.sum(); // sum of the stream

注意:这使用 Collectors.summingLong 简化了流 API 调用链。它允许在遍历集合时避免创建冗余的临时对象。

旁白:您还可以收集您的Callable作为:

List<Callable<Long>> callables = fileList.stream()
.map(fileEntry -> new DataProcessor(fileEntry))
.collect(Collectors.toList());

since I am calling the invokeAll, do I still need to do a shutdown on the Executor?

是的,您必须关闭 ExecutorService。您还可以使用 isShutDown() 确认相同状态API 为:

System.out.println(threadPoolExecutor.isShutdown()); // would return false

关于使用流和可调用对象的 Java ThreadPoolExecutor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53909693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com