thanAccept()不会打印该值

mas*_*ter 1 java concurrency multithreading completable-future

我正在学习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;
    }

}
Run Code Online (Sandbox Code Playgroud)

Esh*_*tIO 5

CompletableFuture开始使用主线程并在完成主线程后完成应用程序.

你需要等待CompletableFuture完成.你能行的:

CompletableFuture.supplyAsync(CompletableFutureTest::counting)
        .thenAccept(System.out::println)
        .get();
Run Code Online (Sandbox Code Playgroud)

get()如果有必要,方法将等待此未来完成