Java 可听未来与可完成未来
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38744943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Listenablefuture vs Completablefuture
提问by Ashutosh Jha
I tried hard but didn't find any article or blog which clearly compares ListenableFuture
and CompletableFuture
, and provides a good analysis.
我很努力,但没有找到任何文章或博客可以清楚地比较ListenableFuture
和CompletableFuture
,并提供很好的分析。
So if anyone can explain or point me to such a blog or article, it will be really good for me.
所以如果有人可以解释或指向我这样的博客或文章,那对我来说真的很好。
采纳答案by Livia Moroianu
Both ListenableFutureand CompletableFuturehave an advantage over its parent class Futureby allowing the caller to "register" in one way or another a callback to be called when the async action has been completed.
无论ListenableFuture和CompletableFuture有超过它的父类的优势未来通过允许呼叫者在这样或那样的回调“注册”当异步动作已经完成被调用。
With Futureyou can do this:
使用Future你可以这样做:
ExecutorService executor = ...;
Future f = executor.submit(...);
f.get();
f.get()
gets blocked until the async action is completed.
f.get()
被阻塞,直到异步操作完成。
With ListenableFutureyou can register a callback like this:
使用ListenableFuture,您可以注册这样的回调:
ListenableFuture listenable = service.submit(...);
Futures.addCallback(listenable, new FutureCallback<Object>() {
@Override
public void onSuccess(Object o) {
//handle on success
}
@Override
public void onFailure(Throwable throwable) {
//handle on failure
}
})
With CompletableFutureyou can also register a callback for when the task is complete, but it is different from ListenableFuturein that it can be completed from any thread that wants it to complete.
使用CompletableFuture,您还可以在任务完成时注册回调,但它与ListenableFuture 的不同之处在于它可以从任何希望它完成的线程中完成。
CompletableFuture completableFuture = new CompletableFuture();
completableFuture.whenComplete(new BiConsumer() {
@Override
public void accept(Object o, Object o2) {
//handle complete
}
}); // complete the task
completableFuture.complete(new Object())
When a thread calls complete on the task, the value received from a call to get() is set with the parameter value if the task is not already completed.
当线程对任务调用完成时,如果任务尚未完成,则使用参数值设置从调用 get() 接收到的值。