1.先定义一个单线程工具类用来做对比
package ForkJoinTest;
import java.util.Random;
public class MakeArray {
public static final int ARRAY_LENGTH= 400000000;
public static final int THRESHOLD= 47;
public static int[] makeArray(){
Random r = new Random();
int[] result =new int[ARRAY_LENGTH];
for( int i = 0 ; i<ARRAY_LENGTH;i++){
result[i]=r.nextInt(ARRAY_LENGTH*3);
}
return result;
}
public static void main(String[] args) {
int count = 0 ;
int[] src = MakeArray.makeArray();
long start = System.currentTimeMillis();
for(int i = 0 ; i < src.length;i++ ){
count = count+src[i];
}
System.out.println("the count is "+count+" spend time:"+(System.currentTimeMillis()-start)+"ms");
}
}
2.写一个类,继承RecursiveTask
package ForkJoinTest;
import java.util.concurrent.RecursiveTask;
public class SumTask extends RecursiveTask<Integer> {
// 当任务拆分到多小的时候不再进行拆分
private final static int THRESHOLD = MakeArray.ARRAY_LENGTH/10;
private int[] src;
private int fromIndex;
private int toIndex;
public SumTask(int[] src, int fromIndex,int toIndex) {
this.src=src;
this.fromIndex=fromIndex;
this.toIndex=toIndex;
}
@Override
protected Integer compute() {
//判断任务的大小是否是合适的范围
if(toIndex-fromIndex<THRESHOLD){
System.out.println(" from index = "+fromIndex+"toIndex="+toIndex);
int count = 0;
for(int i = fromIndex;i<=toIndex;i++){
count=count+src[i];
}
return count;
}else{
int mid = (fromIndex+toIndex)/2;
SumTask left = new SumTask(src, fromIndex, mid);
SumTask right = new SumTask(src, mid+1, toIndex);
invokeAll(left,right);
return left.join()+right.join();
}
}
}
3.进行合并线程测试
public static void main(String[] args) {
int[] src = MakeArray.makeArray();
ForkJoinPool pool = new ForkJoinPool();
SumTask innerFind = new SumTask(src,0,src.length-1);
long start = System.currentTimeMillis();
pool.invoke(innerFind);
System.out.println("The count is "+innerFind.join()+" spend time:"+
(System.currentTimeMillis()-start)+"ms");
}