有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在哪个线程上执行在new CompletableFuture()上注册的回调?

我不熟悉Completable Futures,并试图了解在CompletableFuture上注册的回调是在哪个线程上使用构造函数(new CompletableFuture())构造的

例如:

CompletableFuture<String> future =
        CompletableFuture.supplyAsync(() -> {
            //...
        }, pool);
CompletableFuture<Integer> intFuture =
    future.thenApply(s -> s.length());

thenApply()中的转换已注册,并将在任务完成后立即在与任务相同的线程中执行

CompletableFuture<String> future = new CompletableFuture();
CompletableFuture<Integer> intFuture =
    future.thenApply(s -> s.length());
future.complete("hello");

已注册thenApply()中的转换,并且在使用future.complete("hello")完成任务后将在哪个线程上执行转换?它是在主线程上执行还是在ForkJoinPool.commonPool()上执行


共 (1) 个答案

  1. # 1 楼答案

    新线程只执行Async方法,因此在您的情况下thenApply由主线程执行

    All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() (unless it does not support a parallelism level of at least two, in which case, a new Thread is created to run each task).

    public class TestMain {
    
    public static void main(String[] args) {
    
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return "hello";
        });
        CompletableFuture<Integer> intFuture = future.thenApply(s -> {
            System.out.println(Thread.currentThread().getName());
            return s.length();
        });
    
        CompletableFuture<Integer> intFuture2 = future.thenApply(s -> {
            System.out.println(Thread.currentThread().getName());
            return s.length();
            });
           future.complete("hello");
    
         }
    
     }
    

    输出

    ForkJoinPool.commonPool-worker-1
    main
    main