[英]How to use CompletableFuture to use result of first Callable task as arg to all subsequent Callable tasks?
如何使用 CompletableFuture 将第一个 Callable 任务的结果用作所有后续 Callable 任务的 arg? 我有 3 个任务需要像这样运行:
我尝试在下面执行此操作,但我被困在.thenApply
子句上。
我不能完全让这段代码工作。 在.thenApply
子句中,如何从返回的 object 响应中传递参数?
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.concurrent.*;
public class ThreadPoolTest {
static ExecutorService threadPool = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
CompletableFuture<SumCalculator> cf =
CompletableFuture.supplyAsync(() -> new SumCalculator(100000), threadPool);
Integer initialResult = cf.getNow(null).call();
CompletableFuture<SumCalculator> cf2 = CompletableFuture.completedFuture(initialResult)
.thenApplyAsync((i) -> new SumCalculator(i));
// i want to call 2 or more SumCalulator tasks here
System.out.println("DONE? " + cf2.isDone());
System.out.println("message? " + cf2.getNow(null).call());
threadPool.shutdown();
System.out.println("Program exit.");
}
public static class SumCalculator implements Callable<Integer> {
private int n;
public SumCalculator(int n) {
this.n = n;
}
public Integer call() {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
Uninterruptibles.sleepUninterruptibly(800, TimeUnit.MILLISECONDS);
return sum;
}
}
}
注意:我确实想在 Futures 末尾收集所有 3 个任务的响应作为组合结果列表,可能是 Integer 值的 stream? 在这种情况下,我想对这些值求和。 我想这样做是为了提高多线程的性能。
如果我理解正确:
CompletableFuture<Integer> one =
CompletableFuture.supplyAsync(() -> new SumCalculator(100000).call(), threadPool);
CompletableFuture<Integer> two = one.thenApplyAsync(x -> new SumCalculator(x).call(), threadPool);
CompletableFuture<Integer> three = one.thenApplyAsync(x -> new SumCalculator(x).call(), threadPool);
Integer result = one.join() + two.join() + three.join();
System.out.println(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.