Java从ExecutorService设置回调 [英] Java set a callback from ExecutorService

查看:1537
本文介绍了Java从ExecutorService设置回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个fixedThreadPool,我使用它运行一堆工作线程来实现一个任务与许多组件的并行执行。

I have a fixedThreadPool that I am using to run a bunch of worker threads to achieve parallel execution of a task with many components.

当所有线程都完成后,我使用一个方法(getResult)检索他们的结果(这是相当大的),并将它们写入一个文件。

When all threads have finished, I retrieve their results (which are quite large) using a method (getResult) and write them to a file.

最后,为了节省内存并能够看到中间结果,我希望每个线程一结束执行就将其结果写入文件,然后释放它的内存。

Ultimately, to save memory and be able to see intermediate results, I'd like each thread to write its result to the file as soon as it finishes execution and then free its memory.

通常,我会添加代码到run()方法的结尾。但是,此类中的某些其他对象也调用这些线程,但不希望它们将其结果写入文件,而是使用其结果执行其他计算,最终写入文件。

Ordinarily, I'd add code to that effect to the end of the run() method. However, certain other objects in this class also calls these threads, but DO NOT want them to write their results to file - instead they use their results to perform other calculations, which are eventually written to file.

所以,我想知道是否可以附加一个回调函数到使用ExecutorService完成线程的事件。这样,我可以立即检索其结果并释放内存在那种情况下,但不打破代码,当这些线程用于其他情况下。

So, I was wondering if it's possible to attach a callback function to the event of a thread finishing using the ExecutorService. That way, I can immediately retrieve its result and free the memory in that scenario, but not break the code when those threads are used in other scenarios.

这样的事情可能?

推荐答案

ExecutorService#submit return < a href =http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html =nofollow> FutureTask< T> 帮助您检索结果, ExecutorService#get 方法将阻止执行,直到计算未完成。示例 -

ExecutorService#submit return FutureTask<T> which helps you to retrieve result and the ExecutorService#get method will block execution until the computation is not completed. Example -

ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Long> future = executor.submit(new Callable<Long>(){
       @Override
       public Long call() throws Exception {
           long sum = 0;
           for (long i = 0; i <= 10000000l; i++) {
               sum += i;
           }
           return sum;
       }
});
Long result = future.get();
System.out.println(result);

这篇关于Java从ExecutorService设置回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆