本文介绍了使用Guava FutureCallback接口的Java多线程编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与Java多线程编程有关.
我正在处理创建许多工作程序的主线程,每个工作程序都是一个线程.
为了从工人到主线程获取结果/错误,我将其与Callable和Future一起使用.
我确实在番石榴中找到了 FutureCallback 接口,以从worker中获取异常.
我的问题是如何使用它,因为在网上找不到任何示例.

谢谢!

My question is related to java multithreaded programming.
I am dealing with main thread that creates many workers, every worker is a thread.
To get results/errors from workers to main thread i used with Callable and Future.
I did find in guava FutureCallback interface to get exceptions from worker.
My question is how to use it, because I didn't find any examples on the web.

Thanks !

推荐答案

以下是带有整数结果的示例:

Here is an example with Integer results:

ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(4));
int runs = 100;
for (int k=0; k < runs; k++) {
    Callable<Integer> job = ...; // create the job here
    ListenableFuture<Integer> completion = executor.submit(job);
    Futures.addCallback(completion, new FutureCallback<Integer>() {

        @Override
        public void onFailure(Throwable t) {
            // log error
        }

        @Override
        public void onSuccess(Integer result) {
            // do something with the result
        }

    });
}
executor.shutdown();
while (!executor.isTerminated()) {
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}

这篇关于使用Guava FutureCallback接口的Java多线程编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 02:59