@Slf4j(topic = "e")
public class ForkJoinTest2 extends RecursiveTask<Long> {
private Long start; // 1
private Long end; // 1990900000
// 临界值
private Long temp = 10000L;
public ForkJoinTest2(Long start, Long end) {
this.start = start;
this.end = end;
}
// 计算方法
@Override
protected Long compute() {
ReentrantLock lock = new ReentrantLock();
//tiao
Condition condition = lock.newCondition();
lock.newCondition();
if ((end-start)<temp){
Long sum = 0L;
for (Long i = start; i <= end; i++) {
sum += i;
}
return sum;
}else { // forkjoin 递归
long middle = (start + end) / 2; // 中间值
ForkJoinTest2 task1 = new ForkJoinTest2(start, middle);
task1.fork(); // 拆分任务,把任务压入线程队列
ForkJoinTest2 task2 = new ForkJoinTest2(middle+1, end);
task2.fork(); // 拆分任务,把任务压入线程队列
return task1.join() + task2.join();
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//6596
// test1();
//4872
// test2();
//160
test3();
}
/**
* 单线程的直接10亿累加
*/
public static void test1(){
Long sum = 0L;
long start = System.currentTimeMillis();
for (Long i = 1L; i <= 10_0000_0000; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println("sum="+sum+" 时间:"+(end-start));
}
//最基本的forkjoin 二分查找拆分任务
//拆分任务 关键在于算法 你自己写
public static void test2(){
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinTest2(0L, 10_0000_0000L);
Long sum = forkJoinPool.invoke(task);
// ForkJoinTask<Long> submit = forkJoinPool.submit(task);// 提交任务
// Long sum = submit.get();
long end = System.currentTimeMillis();
System.out.println("sum="+sum+" 时间:"+(end-start));
}
public static void test3(){
long start = System.currentTimeMillis();
//jdk8 stream流式计算
long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
long end = System.currentTimeMillis();
System.out.println("sum="+sum+"时间:"+(end-start));
}
}