[英]How can I immediately pipe tasks from one ThreadPool to another?
我有一個輸入元素列表,我想排隊進入多個ThreadPools。 假設這是我的輸入:
final List<Integer> ints = Stream.iterate(1, i -> i + 1).limit(100).collect(Collectors.toList());
這些是我希望元素依次運行的三個功能:
final Function<Integer, Integer> step1 =
value -> { // input from the ints list
return value * 2;
};
final Function<Integer, Double> step2 =
value -> { // input from the previous step1
return (double) (value * 2); //
};
final Function<Double, String> step3 =
value -> { // input from the previous step2
return "Result: " + value * 2;
};
這些將是每個步驟的池:
final ExecutorService step1Pool = Executors.newFixedThreadPool(4);
final ExecutorService step2Pool = Executors.newFixedThreadPool(3);
final ExecutorService step3Pool = Executors.newFixedThreadPool(1);
我希望每個元素都可以通過step1Pool
並應用step1
。 一旦完成一個元素,其結果應在step2pool
結束,以便可以在此處應用step2
。 一旦step2Pool
中的操作完成,就應將其在step3Pool
排隊,並應應用step3
。 在主線程上,我要等到獲得step3
所有結果。 每個元素的處理順序無關緊要。 只是他們都通過運行step1
> - step2
- > step3
在正確的線程池。
基本上,我想並行化Stream.map
,將每個結果立即推送到下一個隊列,然后等待直到從最后一個線程池獲得ints.size()
結果為止。
有沒有簡單的方法可以用Java實現?
我相信CompletableFuture將在這里為您提供幫助!
List<CompletableFuture<String>> futures = ints.stream()
.map(i -> CompletableFuture.supplyAsync(() -> step1.apply(i), step1Pool)
.thenApplyAsync(step2, step2Pool)
.thenApplyAsync(step3, step3Pool))
.collect(Collectors.toList());
List<String> result = futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
為此,最好使用流:
List<String> stringList = Stream.iterate(1, i -> i + 1)
.limit(100)
.parallel()
.map(step1)
.map(step2)
.map(step3)
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.