java Callable FutureTask Excecuter: How to listen to finished task

瘦欲@ 提交于 2019-12-30 03:19:11

问题


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...


回答1:


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.




回答2:


ExecutorCompletionService

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html




回答3:


If you want to do one task after another its better to do it in the same thread.

Executor executor =
final Runnable runnable = 
executor.execute(new Runnable() {
    public void run() {
         runnable.run();
         // do something after the run() has finished.
    }
 });

This way it will do whatever you want done after the runnable in the same thread and you don't need to poll or use another thread.




回答4:


I'd advise taking a look at the com.google.common.util.concurrent package in Guava, specifically the ListenableFuture type and the code related to it.

Once the next release (r10) is out, it'll be easy to create an ExecutorService that returns ListenableFutures using MoreExecutors.listeningDecorator(ExecutorService). You can also currently wrap your Runnables/Callables in a ListenableFutureTask yourself.

final ListenableFutureTask<?> task = new ListenableFutureTask<Object>(
    runnable, null);
executor.submit(task);
task.addListener(new Runnable() {
  public void run() {
    // do whatever
  }
}, listenerExecutor);


来源:https://stackoverflow.com/questions/6346927/java-callable-futuretask-excecuter-how-to-listen-to-finished-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!