java多线程ForkJoin分支合并
Posted 500年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程ForkJoin分支合并相关的知识,希望对你有一定的参考价值。
java多线程ForkJoin
1、什么是ForkJoin
ForkJoin在JDK1.7出现,并发执行任务!提高效率。大数据了。
大数据:Map Reduce(把大任务拆分为小任务)
2、 ForkJoin特点:工作窃取
里面维护的是双端队列
3、ForkJoin操作
import java.util.concurrent.RecursiveTask;
public class FrokJoinDemo extends RecursiveTask<Long> {
private Long s;
private Long e;
private Long temp = 2L;
public FrokJoinDemo(Long s, Long e) {
this.s = s;
this.e = e;
}
@Override
protected Long compute() {
if (e - s < temp) {
Long sum = 0L;
for (Long i = s; i <= e; i++) {
sum += i;
}
return sum;
} else {
Long middle = (s + e) / 2;// 中间值
FrokJoinDemo task1 = new FrokJoinDemo(s, middle);
task1.fork();// 拆分任务,把任务压如线程队列
FrokJoinDemo task2 = new FrokJoinDemo(middle + 1, e);
task2.fork();
return task1.join() + task2.join();
}
}
}
测试类
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class ForkJoinTest {
public static void main(String[] args) throws Exception {
System.out.println("测试计算机配置:");
System.out.println("CPU:"+Runtime.getRuntime().availableProcessors());
System.out.println("Java虚拟机运行内存:");
System.out.println("可用内存总量:"+Runtime.getRuntime().totalMemory()/1024/1024+"M");
System.out.println("=========== 传统方式 =============");
test1();
System.out.println("=========== ForkJoin =============");
test2();
System.out.println("=========== Stream并行流 =============");
test3();
}
private static void test1() {
long start = System.currentTimeMillis();
Long sum = 0L;
for (Long i = 1L; i <= 10_0000_0000L; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println("sum=" + sum + " 时间:" + (end - start));
}
private static void test2() throws Exception {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> submit = forkJoinPool.submit(new FrokJoinDemo(0L, 10_0000_0000L));
Long sum = submit.get();
long end = System.currentTimeMillis();
System.out.println("sum=" + sum + " 时间:" + (end - start));
}
private static void test3() {
long start = System.currentTimeMillis();
long sum = LongStream.rangeClosed(0, 10_0000_0000L).parallel().reduce(0, Long::sum);
long end = System.currentTimeMillis();
System.out.println("sum=" + sum + " 时间:" + (end - start));
}
}
运行结果对比
测试计算机配置:
CPU:8
Java虚拟机运行内存:
可用内存总量:121M
=========== 传统方式 =============
sum=500000000500000000 时间:7822
=========== ForkJoin =============
sum=500000000500000000 时间:37865
=========== Stream并行流 =============
sum=500000000500000000 时间:400
特别鸣谢:狂神说Java老师的无私奉献
.
.
.
上一篇 java多线程(七) 线程池ThreadPoolExecutor
下一篇 java多线程(九)异步回调Future
以上是关于java多线程ForkJoin分支合并的主要内容,如果未能解决你的问题,请参考以下文章
Java多线程Java的MapReduce框架ForkJoin
JUC高级多线程_09:ForkJoin框架的具体介绍与使用