【问题标题】:CompletableFuture dependent chain to run asynchronouslyCompletableFuture 依赖链异步运行
【发布时间】:2019-11-13 16:34:11
【问题描述】:

如何执行完整的 CompletableFuture 链以使用单独的执行器异步运行

  .thenApply(r -> {
            return validateStudents();
            })
  .thenCompose(r -> {
          return fetchAll(r);
            })
  .thenCompose(r -> {
          return processAll(r);
            })      
  .whenComplete((r, t) -> {

            });
    });

【问题讨论】:

  • 您希望每个方法都由异步线程执行吗?还是一个异步线程的整个链?
  • @Deadpool 全链

标签: java-8 completable-future


【解决方案1】:

您可以使用来自CompletableFutureAsync 方法和默认的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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多