java编程中,如何高效计算1000万个数的相加?
代码实现及测试如下:
private class SumTask extends RecursiveTask<Long> {
private static final int THRESHOLD = 1250000;
private long arr[];
private int start;
private int end;
public SumTask(long[] arr, int start, int end) {
this.arr = arr;
this.start = start;
this.end = end;
}
/**
* 小计
*/
private long subtotal() {
long sum = 0;
for (int i = start; i < end; i++) {
sum += arr[i];
}
return sum;
}
@Override
protected Long compute() {
if ((end - start) <= THRESHOLD) {
return subtotal();
}else {
int middle = (start + end) / 2;
SumTask left = new SumTask(arr, start, middle);
SumTask right = new SumTask(arr, middle, end);
left.fork();
right.fork();
return left.join() + right.join();
}
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException{
int num = Runtime.getRuntime().availableProcessors();
long time = System.currentTimeMillis();
long[] arr = new long[10000000];
for (int i =0 ; i < 10000000; i++) {
arr[i] =i+1;
}
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<Long> result = pool.submit(new ForkJoinTest().new SumTask(arr, 0, arr.length));
System.out.println("最终计算结果: " + result.invoke()+"耗时:"+(System.currentTimeMillis() - time)+",毫秒");
pool.shutdown();
}
测试结果:
使用的cpu内核数量: 4 最终计算结果: 50000005000000耗时:193,毫秒


我发现算法的力量也很重要,最后一种是因为被求和的数组的数据是有规律的,刚好符合等差数列的特征!
网友评论