CompletableFuture runAsync 与 supplyAsync,何时选择一个而不是另一个?
CompletableFuture runAsync vs supplyAsync, when to choose one over the other?
选择一个而不是另一个的理由是什么?在阅读 documentation 后我可以推断出的唯一区别是 runAsync 将 Runnable 作为输入参数,而 supplyAsync 将 Supplier 作为输入参数。
Whosebug post 讨论了将 Supplier 与 supplyAsync 方法结合使用的动机,但它仍然没有回答何时更喜欢其中一个方法。
runAsync以Runnable为入参,returns CompletableFuture<Void>
,表示不return任何结果。
CompletableFuture<Void> run = CompletableFuture.runAsync(()-> System.out.println("hello"));
但是suppyAsync将Supplier作为参数并且returns CompletableFuture<U>
带有结果值,这意味着它不接受任何输入参数但是它returns结果作为输出。
CompletableFuture<String> supply = CompletableFuture.supplyAsync(() -> {
System.out.println("Hello");
return "result";
});
System.out.println(supply.get()); //result
结论: 因此,如果您希望结果被 return 编辑,则选择 supplyAsync
或者如果您只想 运行异步操作,然后选择 runAsync
.
选择一个而不是另一个的理由是什么?在阅读 documentation 后我可以推断出的唯一区别是 runAsync 将 Runnable 作为输入参数,而 supplyAsync 将 Supplier 作为输入参数。
runAsync以Runnable为入参,returns CompletableFuture<Void>
,表示不return任何结果。
CompletableFuture<Void> run = CompletableFuture.runAsync(()-> System.out.println("hello"));
但是suppyAsync将Supplier作为参数并且returns CompletableFuture<U>
带有结果值,这意味着它不接受任何输入参数但是它returns结果作为输出。
CompletableFuture<String> supply = CompletableFuture.supplyAsync(() -> {
System.out.println("Hello");
return "result";
});
System.out.println(supply.get()); //result
结论: 因此,如果您希望结果被 return 编辑,则选择 supplyAsync
或者如果您只想 运行异步操作,然后选择 runAsync
.