码迷,mamicode.com
首页 > 编程语言 > 详细

多线程forkjoin使用样例

时间:2019-04-15 00:59:33      阅读:166      评论:0      收藏:0      [点我收藏+]

标签: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));

}
}

多线程forkjoin使用样例

标签:stat   out   new   []   version   ring   his   catch   xtend   

原文地址:https://www.cnblogs.com/JdestinationL/p/10708318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!