class CalTask extends RecursiveTask<Integer>{
private static final int THRESHOLD=20;
private int arr[];
private int start;
private int end;
public CalTask(int[] arr, int start, int end) {
super();
this.arr = arr;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int sum=0;
if (end-start<THRESHOLD) {
for (int i = start; i < end; i++) {
sum += arr[i];
}
return sum;
} else {
int middle=(start+end)/2;
CalTask left=new CalTask(arr, start, middle);
CalTask ringht=new CalTask(arr, middle, end);
left.fork();
ringht.fork();
return left.join()+ringht.join();
}
}
}
public class Sum {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int[] arr = new int[100];
Random rand = new Random();
int total = 0;
for (int i = 0; i < arr.length; i++) {
int tmp=rand.nextInt(20);
total+=(arr[i]=tmp);
}
System.out.println(total);
ForkJoinPool pool=ForkJoinPool.commonPool();
Future<Integer> future = pool.submit(new CalTask(arr,0,arr.length));
System.out.println(future.get());
pool.shutdown();
}
}无返回值的情况下已经搞懂了但像这样有返回值的情况下,compute方法else块中最后 return left.join()+right.join();理解不了,请大神通俗的解释一下另外这里fork()方法能说明一下吗?书中居然没有说,看例子就是执行的意思?还有commPool的运行状态不是说不受shutdown()影响吗?那这里为何要有这个方法?
添加回答
举报
0/150
提交
取消