使用示例
/**
* 要想使用 Fark—Join,类必须继承 RecursiveAction(无返回值)或者 RecursiveTask(有返回值)
*/
public class Test extends RecursiveTask<Long> {
private long start;
private long end;
public Test(long start, long end) {
this.start = start;
this.end = end;
}
private static final long THRESHOLD = 10000L;
@Override
protected Long compute() {
if (end - start <= THRESHOLD) {
long sum = 0;
for (long i = start; i < end; i++) {
sum += i;
}
return sum;
} else {
long middle = (end + start) / 2;
Test left = new Test(start, middle);
//拆分子任务,压入线程队列
left.fork();
Test right = new Test(middle, end);
right.fork();
//合并并返回
return left.join() + right.join();
}
}
public static void main(String[] args) throws Exception{
//开始时间
long start = System.currentTimeMillis();
//这里需要一个线程池的支持
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<Long> task = new Test(0, 1000000L);
long sum = pool.invoke(task);
pool.shutdown();
//结束时间
long end = System.currentTimeMillis();
System.out.println("时间:"+(end-start)+"; 结果:"+sum);
}
}
结果:
时间:21; 结果:499999500000