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

前端之家收集整理的这篇文章主要介绍了什么时候使用Callable对象在Java Executor中调用call()方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是 example的一些示例代码.我需要知道的是在calllable上调用call()的时候?触发它的是什么?
  1. public class CallableExample {
  2.  
  3. public static class WordLengthCallable
  4. implements Callable {
  5. private String word;
  6. public WordLengthCallable(String word) {
  7. this.word = word;
  8. }
  9. public Integer call() {
  10. return Integer.valueOf(word.length());
  11. }
  12. }
  13.  
  14. public static void main(String args[]) throws Exception {
  15. ExecutorService pool = Executors.newFixedThreadPool(3);
  16. Set<Future<Integer>> set = new HashSet<Future<Integer>>();
  17. for (String word: args) {
  18. Callable<Integer> callable = new WordLengthCallable(word);
  19. Future<Integer> future = pool.submit(callable); //**DOES THIS CALL call()?**
  20. set.add(future);
  21. }
  22. int sum = 0;
  23. for (Future<Integer> future : set) {
  24. sum += future.get();//**OR DOES THIS CALL call()?**
  25. }
  26. System.out.printf("The sum of lengths is %s%n",sum);
  27. System.exit(sum);
  28. }
  29. }

解决方法

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

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

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

猜你在找的Java相关文章