java Callable FutureTask Excecuter: How to listen to finished task

前端 未结 4 1430
我在风中等你
我在风中等你 2020-12-31 16:29

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 R

相关标签:
4条回答
  • 2020-12-31 16:30

    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.

    0 讨论(0)
  • 2020-12-31 16:47

    ExecutorCompletionService

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

    0 讨论(0)
  • 2020-12-31 16:52

    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.

    0 讨论(0)
  • 2020-12-31 16:52

    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);
    
    0 讨论(0)
提交回复
热议问题