package concurrent;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
public class C04_ForkJoin {
/**
* .《实战JAVA高并发程序设计》P117——3.2.9分而治之:Fork/Join
* Fork/Join框架是将大任务分解成小任务,通过合成子任务的子结果而得到结果。
* ForkJoinPool线程池
* ForkJoinTask-----RecurisiveTask : 有返回值,通过 join()接收, 类似的接口有Callable
* --RecursiveAction : 没有返回值
* .下面以计算数列前n项和为例子
*/
public static class CountTask extends RecursiveTask<Long> {
private static final int MAX = 10000; //一个任务最多计算多少项的和
private long start;
private long end;
public CountTask(long start, long end){ this.start = start; this.end = end; }
@Override
protected Long compute() {
long sum = 0;
boolean canCompute = (end - start) < MAX;
if(canCompute){
for(long i=start; i<=end; i++)
sum+=i;
}else{
//分成100个小任务
ArrayList<CountTask> countTasks = new ArrayList<>(100);
long step = (end - start) / 100;
for(long i = start ; i<end ; i+= step + 1){
CountTask task = new CountTask(i, (i + step) < end ? (i + step) : end);
countTasks.add(task);
task.fork(); //执行
}
for(CountTask task : countTasks)
sum += task.join();
}
return sum;
}
}
public static void main(String[] args){
ForkJoinPool forkJoinPool = new ForkJoinPool();
CountTask task = new CountTask(0L, 500000L);
ForkJoinTask<Long> result = forkJoinPool.submit(task);
try{
long res = result.get(); //获得结果
System.out.println("result = " + res);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
forkJoinPool.shutdown();
}
}
console
result = 125000250000