【问题标题】:CompletableFuture runAsync vs supplyAsync, when to choose one over the other?CompletableFuture runAsync vs supplyAsync,什么时候选择一个而不是另一个?
【发布时间】:2020-05-26 06:54:48
【问题描述】:

选择其中之一的理由是什么?阅读documentation 后我能推断出的唯一区别是runAsync 将Runnable 作为输入参数,而supplyAsync 将Supplier 作为输入参数。

Thisstackoverflow 帖子讨论了使用 Supplier 和 supplyAsync 方法背后的动机,但它仍然没有回答何时更喜欢其中一个。

【问题讨论】:

    标签: java asynchronous java-8 completable-future


    【解决方案1】:

    runAsync以Runnable为入参,返回CompletableFuture<Void>,即不返回任何结果。

    CompletableFuture<Void> run = CompletableFuture.runAsync(()-> System.out.println("hello"));
    

    但是suppyAsync 将 Supplier 作为参数并返回带有结果值的CompletableFuture&lt;U&gt;,这意味着它不接受任何输入参数但它返回结果作为输出。

    CompletableFuture<String> supply = CompletableFuture.supplyAsync(() -> {
            System.out.println("Hello");
            return "result";
        });
    
     System.out.println(supply.get());  //result
    

    结论:因此,如果您希望返回结果,请选择supplyAsync,或者如果您只想运行异步操作,请选择runAsync

    【讨论】:

    • 感谢@Deadpool,我应该更仔细地阅读文档。不错的用户名顺便说一句。
    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 2019-02-23
    • 2016-01-27
    • 1970-01-01
    • 2017-01-23
    • 2019-09-07
    • 2010-10-30
    • 1970-01-01
    相关资源
    最近更新 更多