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

前端之家收集整理的这篇文章主要介绍了什么时候使用Callable对象在Java Executor中调用call()方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是 example的一些示例代码.我需要知道的是在calllable上调用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);
  }
}

解决方法

一旦提交了callable,执行程序就会调度callable以便执行.根据执行程序的不同,这可能会直接发生,也可能在线程可用后发生.

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

所以准确地说:在中间提交被调用调用返回之间,调用调用.

原文链接:https://www.f2er.com/java/120810.html

猜你在找的Java相关文章