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

时间:2019-05-29 17:23:56

标签: java completable-future

我是Completable Futures的新手,试图了解使用构造函数(new CompletableFuture())在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 个答案:

答案 0 :(得分:1)

只有Async方法由新线程执行,因此,thenApply由主线程执行

  

所有没有显式Executor参数的异步方法都是使用ForkJoinPool.commonPool()执行的(除非它不支持并行度至少为2,在这种情况下,将创建一个新的Thread来运行每个任务)。

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