Future 和 Promise 有什么区别? [英] What's the difference between a Future and a Promise?
问题描述
Future
和 Promise
有什么区别?
它们都充当未来结果的占位符,但主要区别在哪里?
What's the difference between Future
and Promise
?
They both act like a placeholder for future results, but where is the main difference?
推荐答案
根据 this讨论,Promise
最终被称为 CompletableFuture
以包含在 Java 8 中,并且 它的 javadoc 解释说:
According to this discussion, Promise
has finally been called CompletableFuture
for inclusion in Java 8, and its javadoc explains:
可以明确完成的 Future(设置其值和状态),并且可以用作 CompletionStage,支持在其完成时触发的依赖功能和操作.
A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.
列表中还给出了一个例子:
An example is also given on the list:
f.then((s -> aStringFunction(s)).thenAsync(s -> ...);
请注意,最终的 API 略有不同,但允许类似的异步执行:
Note that the final API is slightly different but allows similar asynchronous execution:
CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);
这篇关于Future 和 Promise 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!