为什么CompletableFuture的thenAccept()没有在主线程上运行

时间:2016-05-02 11:32:56

标签: java completable-future

我在CompletableFuture的supplyAsync()中处理长时间运行的操作,并将结果输入thenAccept()。在某些时候,然后接受()执行主线程但有时它在工作线程上运行。但是我想在主线程上运行thenAccept()操作。这是示例代码。

private void test() {

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
        System.out.println("supplyAsync | I am running on : " + Thread.currentThread().getName());
        return "Hello world";
    }, executorService);

    CompletableFuture<Void> cf3 = cf1.thenAccept(s -> {
        System.out.print("thenAccept | I am running on : " + Thread.currentThread().getName());
        System.out.println(" | answer : " + s);
    });

    cf3.thenRun(() -> {
        System.out.println("thenRun | I am running on : " + Thread.currentThread().getName());
        System.out.println();
    });

}

public static void main(String[] args) {

    App app = new App();
    for(int i = 0; i < 3; i++){
        app.test();
    }
}

结果是:

supplyAsync | I am running on : pool-1-thread-1
thenAccept | I am running on : main | answer : Hello world
thenRun | I am running on : main

supplyAsync | I am running on : pool-2-thread-1
thenAccept | I am running on : main | answer : Hello world
thenRun | I am running on : main

supplyAsync | I am running on : pool-3-thread-1
thenAccept | I am running on : pool-3-thread-1 | answer : Hello world
thenRun | I am running on : pool-3-thread-1

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

查看CompletableFuture的JavaDoc。有趣的部分是关于 CompletionStage 政策的部分。

在那里,您发现使用非异步方法会导致某种情况。如果您随后查看实现,您将最终进入Java Runtime的非公共部分。有一些 UNSAFE 处理意味着可能会发生某种竞争条件。

我建议使用 thenAcceptAsync() thenRunAsync()变体,并将 executorService 变量传递给两个调用。

相关问题