问题描述
我有一个 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.
这种事情有可能吗?
推荐答案
如果可以选择使用 Google Guava,您可以使用 ListenableFuture 接口如下:
If using Google Guava is an option, you could utilize the ListenableFuture interface in the following manner:
- 将
ExecutorService
转换为 ListeningExecutorService 通过MoreExecutors.listeningDecorator(existingExecutorService)
ListeningExecutorService
的submit(Callable<V>)
方法被缩小为返回一个ListenableFuture
,它是未来
.ListenableFuture
有一个addListener()
方法,因此您可以注册一个回调,以便在未来完成时运行.
- Convert an
ExecutorService
to a ListeningExecutorService viaMoreExecutors.listeningDecorator(existingExecutorService)
- The
submit(Callable<V>)
method ofListeningExecutorService
has been narrowed to return aListenableFuture
, which is a subinterface ofFuture
. ListenableFuture
has anaddListener()
method so you can register a callback to be run when the future is completed.
这篇关于Java 从 ExecutorService 设置回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!