java Callable FutureTask Excecuter:如何监听已完成的任务 [英] java Callable FutureTask Excecuter: How to listen to finished task
问题描述
我对执行者服务很陌生。喜欢自己做所有事情,但我认为是时候相信这些服务了。
我想交出 Executer
a 可运行
。执行者将它包装在 FutureTask
中并将其交还给我。现在我调用 done()
方法调查。但是我希望在 done()
方法返回true时收到通知。
有一个 get()
阻塞直到 Runnable
完成的方法,但是我需要为每个作业添加一个额外的线程,只是为了看看它什么时候结束。
我可以给我的执行者一些额外的 Callable
以获得有关完成任务的通知吗? / p>
这里有什么方法?我可以在 run
方法的末尾添加一些代码,但是 done()
可能仍然是false。 。
如果您可以对使用java.util.concurrent.ThreadPoolExecutor做出具体假设,那么您可以使用它的钩子方法; afterExecute()和beforeExecute()。
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
它们不如ListenableFuture那么优雅,但它可能是一个适当的解决方案,前提是您只需要一种类型的侦听器给定的执行器实例。
I'm quite new to executer services. Liked doing everything myself, but I think it's time to trust these services.
I want to hand by Executer
a Runnable
. The executer wraps that in a FutureTask
and hands it back to me. Now I call poll the done()
method. But I would like to be notified when then done()
method would return true.
There is a get()
method that blocks until the Runnable
has finished, but then I would need a extra thread for every job, just to see when it's finished.
Can I hand my executer some extra Callable
to get notified about the task finishing?
What's the way to go here? I could add some code to the end of the run
method, but then done()
might still be false...
If you can make a specific assumption of using a java.util.concurrent.ThreadPoolExecutor, then you can use its hook methods; afterExecute() and beforeExecute().
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
They are not as elegant as the ListenableFuture, but it might be an adequate solution provided you need only one type of a "listener" for a given executor instance.
这篇关于java Callable FutureTask Excecuter:如何监听已完成的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!