package com.example.juc;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;
/**
* @program: demo
* @description:
* @author: ZCY
**/
public class ForkJoinDemo extends RecursiveTask<Long> {
private Long start;
private Long end;
//临界值
private Long temp = 10000L;
public ForkJoinDemo(Long start, Long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if (end - start > temp) {
Long middle = (start + end) / 2; //中间值
ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
task1.fork();
ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
task2.fork();
return task1.join() + task2.join();
} else {
Long sum = 0L;
for (Long i = start; i <= end; i++) {
sum += i;
}
return sum;
}
}
}
class IncrementDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//test1();//3816
//test2();//7268
//test3();//150
}
static void test1() {
long start = System.currentTimeMillis();
Long sum = 0L;
for (int i = 0; i < 10_0000_0000; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println(sum + ",用时:" + (end - start));
}
static void test2() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinDemo fork = new ForkJoinDemo(0L, 10_0000_0000L);
ForkJoinTask<Long> submit = forkJoinPool.submit(fork);
Long sum = submit.get();
long end = System.currentTimeMillis();
System.out.println(sum + ",用时:" + (end - start));
}
static void test3() {
long start = System.currentTimeMillis();
long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
long end = System.currentTimeMillis();
System.out.println(sum + ",用时:" + (end - start));
}
}
ForkJoin学习
最新推荐文章于 2024-01-13 13:03:52 发布