ExecutorService和Callable

时间:2017-06-21 12:56:13

标签: java concurrency future executorservice callable

我正在实现一个简单的求和程序,使用递归多线程方法总结一个整数数组。(ExecutorService& Callable)。

但我得到了大量的例外

public class ExecutorServiceSum implements Callable<Integer> {
 int[] a;
 int lo;
 int hi;
 static ExecutorService ex;

 ExecutorServiceSum(ExecutorService ex, int[] a, int lo, int hi) {
  this.a = a;
  this.lo = lo;
  this.hi = hi;
 }
 @Override
 public Integer call() throws Exception {
  int size = hi - lo;
  if (size == 1) {
   return a[hi];
  }
  //exit of the recursion 

  int mid = size / 2;
  ExecutorServiceSum e1 = new ExecutorServiceSum(ex, a, lo, lo + mid);
  ExecutorServiceSum e2 = new ExecutorServiceSum(ex, a, lo + mid, hi);
  //branching to subproblems

  Future<Integer> f1 = ex.submit(e1);
  Future<Integer> f2 = ex.submit(e2);

  return f1.get() + f2.get();
 }

 public static void main(String[] args) throws InterruptedException,
 ExecutionException {
  int[] a = new int[200000];
  for (int i = 0; i < a.length; i++) {
   a[i] = 1;
  }
  //this is the array the programm needs to sum up 

  ExecutorService exs = Executors.newFixedThreadPool(20);
  //creating a ThreadPool using newFixedThreadPool

  ExecutorServiceSum ess = new ExecutorServiceSum(ex, a, 0, a.length);
  //creating a Callable task obejct 

  Future < Integer > f3 = exs.submit(ess);
  //submitting the Callable task object to the ThreadPool
  //store the result in Future object

  System.out.println(f3.get());
 }
}

以下是例外情况:

Exception in thread "main" java.util.concurrent.ExecutionException: 
java.lang.NullPointerException
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at ExecutorServiceSum.main(ExecutorServiceSum.java:54)
Caused by: java.lang.NullPointerException
    at ExecutorServiceSum.call(ExecutorServiceSum.java:31)
    at ExecutorServiceSum.call(ExecutorServiceSum.java:1)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

问题:

  1. 为什么get()方法获取未知来源?

  2. 未来对象包含未完成的返回结果?

  3. 如何修复此代码?

0 个答案:

没有答案