-
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();
-
}
转载:https://blog.csdn.net/byt420/article/details/105987512
查看评论