听觉未来与完成未来

编程入门 行业动态 更新时间:2024-10-14 12:22:01
本文介绍了听觉未来与完成未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很努力,但没有找到任何可以明显比较 ListenableFuture 和 CompletableFuture 的文章或博客,并提供了很好的分析。

I tried hard but didn't find any article or blog which clearly compares ListenableFuture and CompletableFuture, and provides a good analysis.

因此,如果有人可以向我解释或指向这样的博客或文章,那对我真的很有益。

So if anyone can explain or point me to such a blog or article, it will be really good for me.

推荐答案

ListenableFuture 和 CompletableFuture 均比其父类具有优势未来:允许调用者以一种方式注册或在异步操作完成后调用回调。

Both ListenableFuture and CompletableFuture have an advantage over its parent class Future by allowing the caller to "register" in one way or another a callback to be called when the async action has been completed.

未来,您可以执行以下操作:

With Future you can do this:

ExecutorService executor = ...; Future f = executor.submit(...); f.get();

f.get()被阻止,直到

使用 ListenableFuture ,您可以注册如下回调:

With ListenableFuture you can register a callback like this:

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 } })

使用 CompletableFuture ,您还可以为任务完成时注册一个回调,但这是与 ListenableFuture 的不同之处在于,它可以从任何希望完成的线程中完成。

With CompletableFuture you can also register a callback for when the task is complete, but it is different from ListenableFuture in that it can be completed from any thread that wants it to complete.

CompletableFuture completableFuture = new CompletableFuture(); completableFuture.whenComplete(new BiConsumer() { @Override public void accept(Object o, Object o2) { //handle complete } }); // complete the task completableFutureplete(new Object())

当线程任务完成后,如果任务尚未完成,则从get()调用接收的值将设置为参数值。

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.

了解CompletableFuture

更多推荐

听觉未来与完成未来

本文发布于:2023-11-25 02:23:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未来   听觉

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!