标签:stat out new [] version ring his catch xtend
public class MakeArray {
public static final int ARRAYLENGTH = 1000;
public static int[] makeArray() {
Random r = new Random();
int[] oRtn = new int[ARRAYLENGTH];
for (int i = 0; i < oRtn.length; i++) {
oRtn[i] = r.nextInt(ARRAYLENGTH*3);
}
return oRtn;
}
}
public class ForkJoinTest {
private static final int THREADHOLD = MakeArray.ARRAYLENGTH/10;
private static class SumArray extends RecursiveTask<Integer>{
private static final long serialVersionUID = 1L;
private int[] array;
private int fromIndex;
private int endIndex;
public SumArray(int[] array, int fromIndex, int endIndex) {
super();
this.array = array;
this.fromIndex = fromIndex;
this.endIndex = endIndex;
}
@Override
protected Integer compute() {
int count = 0;
if(endIndex-fromIndex<=THREADHOLD) {
for (int i = fromIndex; i <= endIndex; i++) {
count+=array[i];
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return count;
}else {
int mid = (endIndex+fromIndex)/2;
SumArray left = new SumArray(array, fromIndex, mid);
SumArray right = new SumArray(array, mid+1, endIndex);
invokeAll(left,right);
return left.join()+right.join();
}
}
}
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool();
int[] src = MakeArray.makeArray();
SumArray sum = new SumArray(src, 0, src.length-1);
long start = System.currentTimeMillis();
pool.invoke(sum);
System.out.println("count:"+sum.join()+" time:"+(System.currentTimeMillis()-start));
}
}
标签:stat out new [] version ring his catch xtend
原文地址:https://www.cnblogs.com/JdestinationL/p/10708318.html