Callable接口使用实例源码说明。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public class CallableTest implements Callable<Integer>{
int [] a;
int s, e;
public CallableTest(int [] a, int s, int e){
this.a = a;
this.s = s;
this.e = e;
}
public Integer call() throws Exception {
int tmpSum = 0;
for(int i=s; i<=e; i++){
tmpSum += a[i];
}
return tmpSum;
}
public static void main(String [] args) throws InterruptedException, ExecutionException{
ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();
ExecutorService exc = Executors.newCachedThreadPool();
int [] a = {1,2,3,4,5,6,7,8,9,20};
for(int i=0; i<2; i++){
results.add(exc.submit(new CallableTest(a, i*5, (i+1)*5-1)));
}
exc.shutdown();
int sum = 0;
for(Future<Integer> r: results){
int tmp = r.get();
System.out.println(“tmp = “+tmp);
sum += tmp;
}
System.out.println(“sum = “+sum);
}
}