ForkJoin框架,可做同步和异步处理,可有返回值和无返回值调用。
invokeAll为同步调用;
execute为异步调用;
RecursiveAction,用于没有返回结果的任务;
RecursiveTask,用于有返回值的任务;
这里用同步调用实现累加
package com.cz.mhm.forkjoin.sum;
import java.lang.reflect.Array;
import java.util.Random;
public class ArrayUtils {
private static int num = 100000000; //100000000
public static Integer[] getArrays() {
Integer[] arr = new Integer[num];
Random r = new Random();
for (int i=0;i<num;i++) {
arr[i] = r.nextInt(100);
// System.out.println(arr[i]);
}
return arr;
}
public static void main(String[] args) {
Integer[] arr = ArrayUtils.getArrays();
int fromIndex = 0;
int toIndex = arr.length - 1;
int mid = (toIndex - fromIndex)/ 2;
System.out.println("[" + fromIndex + "-" + mid + "], " + "[" + (mid+1) + "-" + toIndex + "]");
}
}
package com.cz.mhm.forkjoin.sum.sync;
import java.util.concurrent.RecursiveTask;
public class SumTask extends RecursiveTask<Integer> {
// 以50为边界
private static int THRESHOLD = 50;
private Integer[] src;
private int fromIndex;
private int toIndex;
public SumTask(Integer[] src, Integer fromIndex, Integer toIndex) {
this.src = src;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
}
@Override
protected Integer compute() {
if((toIndex - fromIndex) < THRESHOLD) {
int count = 0;
for (int i=fromIndex; i<toIndex; i++) {
count = count + src[i];
}
return count;
} else {
int mid = (toIndex - fromIndex) / 2;
SumTask leftTask = new SumTask(this.src, fromIndex, mid);
SumTask rightTask = new SumTask(this.src, mid+1, toIndex);
invokeAll(leftTask, rightTask);
return leftTask.join() + rightTask.join();
}
}
}
package com.cz.mhm.forkjoin.sum.sync;
import com.cz.mhm.forkjoin.sum.ArrayUtils;
public class SumWithFJ {
public static void main(String[] args) {
Integer[] arr = ArrayUtils.getArrays();
long c1 = System.currentTimeMillis();
int count = 0;
for (int i=0; i<arr.length; i++) {
count = count + arr[i];
}
long c2 = System.currentTimeMillis();
System.out.println("普通耗时" + (c2-c1) + "毫秒, count:" + count);
long c3 = System.currentTimeMillis();
SumTask mytask = new SumTask(arr, 0, arr.length-1);
long c4 = System.currentTimeMillis();
System.out.println("forkjoin耗时" + (c4-c3) + "毫秒, count:" + count);
}
}