首页 > 解决方案 > 在 CompletableFuture 中使用 thenXXXX 与 thenXXXXAsync 方法的性能影响

问题描述

我对使用 JDK 8 的 CompletableFuture 类的 thenXXXX 和 thenXXXXAsync 方法有疑问。根据我的理解,thenApply将使用与未来早期执行相同的线程,然后thenApplyAsync使用池中的任何线程。

代码_1:

CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> tcf.task("FIRST"), executors)
        .thenApply(a -> {
                logger.log(Level.INFO, "Thread Id - 1 " + Thread.currentThread().getName());
                ////Some operations
         })
        .thenApply(a -> {
                logger.log(Level.INFO, "Thread Id - 2 " + Thread.currentThread().getName());
                ////Some operations
         });

输出:
线程 ID - 1:pool-1-thread-1

线程 ID - 2:pool-1-thread-1

代码_2:

CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> tcf.task("FIRST"), executors)
        .thenApplyAsync(a -> {
                logger.log(Level.INFO, "Thread Id - 1 " + Thread.currentThread().getName());
                ////Some operations
         }, executors)
        .thenApplyAsync(a -> {
                logger.log(Level.INFO, "Thread Id - 2 " + Thread.currentThread().getName());
                ////Some operations
         }, executors);

输出:
线程 ID - 1:pool-1-thread-2

线程 ID - 2:pool-1-thread-3

哪个是最好的使用方法?在 Code_2 中,任务从一个线程移动到另一个线程。它会影响任何性能吗?

谢谢

标签: javamultithreadingperformancejava-8completable-future

解决方案


推荐阅读