我如何执行完整的CompletableFuture链以使用单独的执行程序异步运行
.thenApply(r -> {
return validateStudents();
})
.thenCompose(r -> {
return fetchAll(r);
})
.thenCompose(r -> {
return processAll(r);
})
.whenComplete((r, t) -> {
});
});
答案 0 :(得分:1)
您可以使用CompletableFuture中的Async
方法和默认的ForkJoinPool
所有没有显式Executor参数的异步方法都是使用ForkJoinPool.commonPool()执行的(除非它不支持并行度至少为两个,在这种情况下,将创建一个新的线程)运行每个任务)
System.out.println(Thread.currentThread().getName());
CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName());
return "supplyAsync";
}).thenApplyAsync(supply->{
System.out.println(Thread.currentThread().getName()+"----"+supply);
return "applyAsync";
}).thenComposeAsync(compose->{
System.out.println(Thread.currentThread().getName()+"----"+compose);
return CompletableFuture.completedStage("composeAsync");
});
输出:
main
ForkJoinPool.commonPool-worker-3
ForkJoinPool.commonPool-worker-3----supplyAsync
ForkJoinPool.commonPool-worker-3----applyAsync
您还可以定义自定义线程池,并且可以使用该线程池
ExecutorService pool = Executors.newFixedThreadPool(1);
System.out.println(Thread.currentThread().getName());
CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName());
return "supplyAsync";
},pool).thenApplyAsync(supply->{
System.out.println(Thread.currentThread().getName()+"----"+supply);
return "applyAsync";
},pool).thenComposeAsync(compose->{
System.out.println(Thread.currentThread().getName()+"----"+compose);
return CompletableFuture.completedStage("composeAsync");
},pool);
输出:
main
pool-1-thread-1
pool-1-thread-1----supplyAsync
pool-1-thread-1----applyAsync