为什么除非我们在 CompletableFuture 上调用 get 方法,否则 CompletableFuture 中的 runAsync 方法不会执行?

why runAsync method in CompletableFuture is not executing until unless we are calling get method on CompletableFuture?

所以理想情况下,当我们使用线程概念时,它会 运行 异步执行任务, 所以在下面的代码片段中:

  CompletableFuture result=  CompletableFuture.runAsync(()->{
        System.out.println("1st Task Completed");

    });

虽然 运行在 main 方法中使用此代码,但它没有打印“第一个任务已完成”。 如果我将输入 result.get() 那么它会打印“第一个任务已完成”。 每当我们调用 get 方法时,任务是否正在执行?

如果这是您 main 中唯一的代码,main 方法很可能会 return (并结束您的程序),然后异步任务才有机会 运行.

只需在您的代码后添加一个 Thread.sleep(1000); 或类似的内容,您应该会看到预期的输出。

但是我们真的不知道我们需要等待多长时间,所以更稳健的方法是使用同步机制,例如:

CountDownLatch done = new CountDownLatch(1);
CompletableFuture.runAsync(()->{
  System.out.println("1st Task Completed");
  done.countDown();
});
done.await();

程序的执行与字符串的打印并行发生,这是一种异步执行(也称为未来)。调用 get() 方法,阻塞主线程并等待直到 future 完成或抛出异常。

在您分享的示例中,程序在打印字符串之前就退出了。仅作为示例,可以使用 CountDownLatch 或 Thread.sleep()。 get() 足以满足此用例,就个人而言,应避免使用任何其他结构。

有一篇文章,CompletableFuture : A Simplified Guide to Async Programming,读起来很有趣,它简化了 CompletableFuture 的用法