public static void main(String[] args) {
ForkJoinTask<Long> myForkJoinPool = new MyForkJoinPool(1L,999999999L);
ForkJoinPool pool = ForkJoinPool.commonPool();
Future<Long> future = pool.submit(myForkJoinPool); //提交分解的SumTask 任务
try {
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
}
}
import java.util.concurrent.RecursiveTask;
/**
* @author shiqil.liu
* @date 2019-08-23 16:31
*/
public class MyForkJoinPool extends RecursiveTask<Long> {
private long start;
private long end;
public static final long MAX_SIZE = 10000;
public MyForkJoinPool(long start, long end) {
this.start = start;
this.end = end;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
@Override
protected Long compute() {
long sum = 0;
if(end -start < MAX_SIZE) {
for(long i=start;i<=end;i++) {
sum += i;
}
return sum;
} else {
long mid = (end+start) / 2 ;
MyForkJoinPool myForkJoinPool1 = new MyForkJoinPool(start, mid);
MyForkJoinPool myForkJoinPool2 = new MyForkJoinPool(mid+1, end);
//invokeAll(myForkJoinPool1,myForkJoinPool1);
myForkJoinPool1.fork();
myForkJoinPool2.fork();
return myForkJoinPool1.join()+myForkJoinPool2.join();
}
}
}