thanAccept() 不打印值

thanAccept() does not print the value

我正在学习 CompletableFuture,在下面的代码片段中,thenAccept() 方法没有打印应该是 10 的值,但程序编译无一例外。谁能给我解释一下这是什么问题?

import java.util.concurrent.*;
import java.util.stream.Stream;

public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(CompletableFutureTest::counting).thenAccept(System.out::println);
        System.out.println("xD");
    }
    public static int counting() {


        Stream.iterate(1, integer -> integer +1).limit(5).forEach(System.out::println);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 10;
    }

}

您的 CompletableFuture 开始使用主线程,主线程完成后您的应用程序结束。

您需要等待 CompletableFuture 完成。 你可以做到:

CompletableFuture.supplyAsync(CompletableFutureTest::counting)
        .thenAccept(System.out::println)
        .get();

方法 get() 必要时等待此未来完成