package com.gc.test;
/**
* Created by jiji on 2018/12/30.
*/
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import org.junit.Test;
//
/**
*
* 计算0L-------100000000000L 进行累加求和
*
*
*
*/
public class CalultTestSum {
public static void main(String arg[]){
Instant start = Instant.now();
ForkJoinPool pool = new ForkJoinPool();
ForkJoinSumCalculate forkJoinSumCalculate = new ForkJoinSumCalculate(0L, 100000000000L);
Long invoke = pool.invoke(forkJoinSumCalculate);
System.out.print(invoke);
Instant end = Instant.now();
System.out.print("花费时间:"+ Duration.between(start,end).toMillis());
/**
*
*
* 使用 fork join
*
*
* 计算范围 结果 时间
* 1000000000L 500000000500000000 花费时间:436
* 10000000000L -5340232216128654848 花费时间:4379
* 100000000000L 932356074711512064 花费时间:43193
*/
}
/** 普通for循环等待2分钟未计算出结果
*
* 计算范围 结果 时间
* 1000000000L 500000000500000000 花费时间:406
* 10000000000L -5340232216128654848 花费时间:5860
* 100000000000L 932356074711512064 花费时间:39409
*
*/
@Test
public void testFor(){
Instant start = Instant.now();
long sum= 0L;
for (long i=0L;i<=100000000000L;i++){
sum+=i;
}
Instant end = Instant.now();
System.err.println(sum);
System.out.print("花费时间:"+ Duration.between(start,end).toMillis());
}
}
class ForkJoinSumCalculate extends RecursiveTask<Long>{
private static final long serialVersionUID = 1L;
private long start;
private long end ;
private static final long THURSHOLD = 10000000L;
@Override
protected Long compute() {
long length = end -start;
if(length<=THURSHOLD){//小于临界值
long sum =0l;
for (long i =start;i<=end;i++){
sum +=i;
}
return sum;
}else {
long middle = (start+end)/2;
ForkJoinSumCalculate left = new ForkJoinSumCalculate(start,middle);
left.fork();
ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle+1,end);
right.fork();
return left.join()+right.join();
}
}
public ForkJoinSumCalculate(long start,long end){
this.start =start;
this.end=end;
}
}