什么时候使用Callable对象在Java Executor中调用call()方法?

时间:2010-03-17 11:34:58

标签: java concurrency

这是example的一些示例代码。我需要知道的是在call()被调用时被调用?触发它的原因是什么?

public class CallableExample {

public static class WordLengthCallable
    implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
}

public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future<Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable); //**DOES THIS CALL call()?**
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();//**OR DOES THIS CALL call()?**
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }
}

3 个答案:

答案 0 :(得分:9)

一旦你有submitted可调用,执行程序将调度可调用执行。根据执行程序的不同,这可能会直接发生,也可能在线程可用后发生。

另一方面,调用get只等待检索计算结果。

准确地说:在调用submit和调用get之间的某个地方,调用callable。

答案 1 :(得分:4)

使用Executor的整个想法是,在完全调用该方法时,您不应该关心

唯一保证的是,当get()的{​​{1}}返回时,该方法将被执行。

何时调用它取决于您使用的Future。使用您在示例中使用的固定线程池,只要有一个空闲线程就会调用Executor方法,并且队列中给定任务前面没有其他任务(只要有足够多的任务,您将在示例中的任何给定时间运行3个call()方法调用。)

答案 2 :(得分:0)

“可调用的时间表”的答案在于java.util.concurrent.ThreadPoolExecutor #execute实现(默认)