【问题标题】:why runAsync method in CompletableFuture is not executing until unless we are calling get method on CompletableFuture? [duplicate]为什么除非我们在 CompletableFuture 上调用 get 方法,否则 CompletableFuture 中的 runAsync 方法不会执行? [复制]
【发布时间】:2021-08-12 16:02:57
【问题描述】:

所以理想情况下,当我们使用线程概念时,它会异步运行任务, 所以在下面的sn-p中:

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

    });

在 main 方法中运行此代码时,它不会打印 "1st Task Completed" 。 如果我输入 result.get() 那么它会打印“第一个任务完成”。 那么,当我们调用 get 方法时,任务是否正在执行?

【问题讨论】:

    标签: java java-8 completable-future


    【解决方案1】:

    如果这是您的 main 中的唯一代码,main 方法很可能会在异步任务有机会运行之前返回(并结束您的程序)。

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

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

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

    【讨论】:

      【解决方案2】:

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

      在您分享的示例中,程序在字符串打印之前退出。仅作为示例,可以使用 CountDownLatch 或 Thread.sleep()。 get() 对于这个用例来说已经足够了,就个人而言,应该避免任何其他构造。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-11
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多