代码
import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ArraySumDemo {
public static int n = 1000000;
public static void main(String[] args) {
int[] ints = new int[n];
for (int i = 1; i <= n; i++) {
ints[i - 1] = i;
}
System.out.println(Arrays.toString(ints));
ForkJoinPool.commonPool().invoke(new CTask(ints, 0, ints.length));
}
}
class CTask extends RecursiveTask<Void> {
private int[] ints;
int start;
int end;
public CTask(int[] ints, int start, int end) {
this.ints = ints;
this.start = start;
this.end = end;
}
@Override
protected Void compute() {
if (end - start <= 100) {
for (int i = start; i < end; i++) {
System.out.print(ints[i] + ",");
}
System.out.println();
return null;
}
int mid = (start + end) / 2;
CTask task1 = new CTask(this.ints, start, mid);
CTask task2 = new CTask(this.ints, mid, end);
invokeAll(task1, task2);
task1.join();
task2.join();
return null;
}
}