簡體   English   中英

為什么CompletableFuture的thenAccept()沒有在主線程上運行

[英]Why CompletableFuture 's thenAccept() not running on the main thread

我在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

我怎樣才能解決這個問題 ?

看一下CompletableFuture的JavaDoc。 有趣的部分是關於CompletionStage政策的部分。

在那里,您會發現使用非異步方法會產生一種或者一種情況。 如果您隨后查看實現,您將最終進入Java Runtime的非公共部分。 有一些UNSAFE處理意味着可能會發生某種競爭條件。

我建議使用thenAcceptAsync()thenRunAsync()變體,並將executorService變量傳遞給兩個調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM