package com.uncle.forktest;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
public class ForkJoin {
public static void main(String[] args) throws ExecutionException, InterruptedException {
long time1 = System.currentTimeMillis();
// 创建线程池
ForkJoinPool forkJoinPool = new ForkJoinPool();
CountTask countTask = new CountTask(1, 1000000000);
ForkJoinTask<Long> submit = forkJoinPool.submit(countTask);
System.out.println("这个是算出来的数" + submit.get());
long time2 = System.currentTimeMillis();
System.out.println("这是算出来的运行时间" + (time2 - time1));
}
/**
* 线程池
* 任务 拆解 合并
* 1-100
* computer 计算方法(拆解 合并)
* fork 拆解
* join 获取结果
* <p>
* RecursiveTask RecursiveAction
*/
static class CountTask extends RecursiveTask<Long> {
int start;
int end;
public CountTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long sum = 0;
if (end - start <= 2) {
for (int i = start; i <= end; i++) {
sum += i;
}
} else {
int mid = (start + end) / 2;
CountTask leftTask = new CountTask(start, mid);
CountTask rightTask = new CountTask(mid + 1, end);
leftTask.fork();
rightTask.fork();
long leftResult = leftTask.join();
long rightResult = rightTask.join();
sum = leftResult + rightResult;
}
return sum;
}
}
}
02-28
700
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)