//Fork/join 框架
public class ForkJoinCalculate extends RecursiveTask<Long> {
private long start;
private long end;
public ForkJoinCalculate(long start, long end) {
this.start = start;
this.end = end;
}
public ForkJoinCalculate() {
}
private static final long THRESHOLD = 10000;
@Override
protected Long compute() {
long length = end - start;
if(length < THRESHOLD) {
long sum = 0;
for(long i = start; i <= end ; i ++){
sum += i;
}
return sum;
}else{
long middle = (end + start) / 2;
ForkJoinCalculate left = new ForkJoinCalculate(start,middle);
left.fork();// 拆分子任务 同时压入线程队列
ForkJoinCalculate right = new ForkJoinCalculate(middle+1,end);
right.fork();
return left.join() + right.join();
}
}
}
测试
@Test
public void testForkJoin(){
// long start = System.currentTimeMillis();
Instant start = Instant.now(); //java 8
ForkJoinPool pool = new ForkJoinPool();
ForkJoinCalculate task = new ForkJoinCalculate(0,100000000L);
Long invoke = pool.invoke(task);
// long end = System.currentTimeMillis();
Instant end = Instant.now();
System.out.println("耗费时间:"+ Duration.between(start,end).toMillis());
System.out.println(invoke);
}
/**
* java 8
*/
@Test
public void test1(){
Instant start = Instant.now();
long reduce = LongStream.rangeClosed(0, 100000000L)
.parallel()
.reduce(0, Long::sum);
Instant end = Instant.now();
System.out.println(Duration.between(start,end).toMillis());
System.out.println(reduce);
}