[英]Java ThreadPoolExexecutor using streams and Callables
我有一個實現Callable
的類,並且它具有重寫call
並返回Long
。
我創建了一個List
的Callable<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()
所有返回值future.get()
。
另外,由於我正在調用invokeAll,所以我仍然需要關閉執行器嗎?
您需要的是Collectors.summingLong
:
.collect(Collectors.summingLong(r -> r));
其中r -> r
只是一個ToLongFunction
,它使Callable
s返回的每個Long
占一個long
。
另外,由於我正在調用invokeAll,所以我仍然需要關閉執行器嗎?
ExecutorService.invokeAll
沒有記錄自動關機。 所以你需要自己關閉它
您可以使用Stream.mapToLong
映射future.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調用鏈。 它允許避免遍歷集合時創建冗余的臨時對象。
除了 :您還可以按以下方式collect
Callable
:
List<Callable<Long>> callables = fileList.stream()
.map(fileEntry -> new DataProcessor(fileEntry))
.collect(Collectors.toList());
由於我正在調用invokeAll,因此我仍然需要關閉執行器嗎?
是的,您必須關閉ExecutorService
。 您還可以使用isShutDown()
API確認相同狀態:
System.out.println(threadPoolExecutor.isShutdown()); // would return false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.