JAVA并发编程3
ForkJoin
并行执行任务,提高效率。双端队列,可以工作窃取。
代码
常规相加
private static void normalAdd() {
long sum = 0L;
long start = System.currentTimeMillis();
for (long i = 1L; i <= 10_0000_0000L; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println("sum =" + sum + " cost " + (end - start));
}
forkjoin相加
private static void forkJoin() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinBean forkJoinBean = new ForkJoinBean(0L, 10_0000_0000L);
ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinBean);
Long sum = submit.get();
long end = System.currentTimeMillis();
System.out.println("sum =" + sum + " cost " + (end - start));
}
public class ForkJoinBean extends RecursiveTask<Long> {
private long start;
private long end;
private static final long THRESHOLD = 10000L;
public ForkJoinBean(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if ((end - start) < THRESHOLD) {
long sum = 0L;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
} else {
long mid = (end + start) / 2;
ForkJoinBean upTask = new ForkJoinBean(start, mid);
upTask.fork();
ForkJoinBean downTask = new ForkJoinBean(mid + 1, end);
downTask.fork();
return upTask.join() + downTask.join();
}
}
}
流相加
private static void streamJoin() {
long start = System.currentTimeMillis();
long sum = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0, Long::sum);
long end = System.currentTimeMillis();
System.out.println("sum =" + sum + " cost " + (end - start));
}