听觉未来与完成未来

听觉未来与完成未来

本文介绍了听觉未来与完成未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很努力,但没有找到任何可以明显比较 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
    completableFuture.complete(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.

这篇关于听觉未来与完成未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:27