【问题标题】:Calling a function when a task is done完成任务时调用函数
【发布时间】:2014-12-26 13:27:19
【问题描述】:

我开始使用 executor 服务,我想知道当一个任务完成后我将如何调用一个函数。我见过这个函数 http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#isDone--

但我不确定如何连接它以在我的代码中调用函数 endoftheroad()

这是我的代码

//import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//import java.util.concurrent.Future;
//import java.util.concurrent.TimeUnit;
import java.util.*;

public class Pooler {

        public static int add(int x, int y){
        int c = x + y;
        return c;
        }
        public static int endoftheroad(){
        int the_end = 0;
        return the_end;
        }

    public static void main(String args[]) {
       ExecutorService service = Executors.newFixedThreadPool(10);
       for (int i =0; i<100; i++){
       Random randomno = new Random();
       int value = randomno.nextInt();
       service.submit(new Task(add(value,value)));
       }
    }

}


final class Task implements Runnable{
    private int taskId;

    public Task(int id){
        this.taskId = id;
    }

    @Override
    public void run() {
        System.out.println("Task ID : " + this.taskId +" performed by " 
                           + Thread.currentThread().getName());
    }

}

【问题讨论】:

    标签: java multithreading executorservice


    【解决方案1】:

    你的成本有问题

    a) add 在当前线程中执行。什么都没有,除了打印输出是在 executors 线程中执行的。

    b) 道路尽头函数不做任何事情,所以调用与否无关紧要。

    c) 你忽略了返回的 Future 使得使用它变得困难。

    要回答您的问题,您可以在 Java 8 中使用 CompleableFuture。不过,更简单的解决方案是;

    • 将循环中的所有代码移到 run() 内。
    • 在 run() 方法结束时调用此代码后运行的函数。

    【讨论】:

      【解决方案2】:

      很简单,你当前的任务一旦完成就向执行者提交一个新任务:

      public void run() {
        doSomeStuff();
        executor.submit(new FinishHimTask());
      }
      

      但是您应该记住,如果提交的任务非常小,那么在当前线程中执行它可能会更高效,因为创建新任务并将其添加到 Executor 也需要一些时间.

      【讨论】:

        【解决方案3】:

        如果您的代码需要在 Java 7 下运行,请查看 Google 的 guava 库中的 ListenableFuture。如果您可以选择使用 guava,ListenableFuture 类可以提供您所需要的内容。 https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained有教程。

        如果你有 Java 8,来自 JDK 的 CompletableFuture 是另一种选择。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-05
          • 2020-03-21
          • 1970-01-01
          • 2013-12-21
          • 1970-01-01
          • 2015-08-22
          • 1970-01-01
          相关资源
          最近更新 更多