ForkJoin分支合并
什么是ForkJoin
ForkJoin在JDK1.7 ,并行执行任务!提高效率,大数据量
大数据:Map Reduce(把大任务拆分成小任务)
ForkJoin特点
工作窃取: (这个里面维护的都是双端队列)
ForkJoin 例子
去继承其中一个
使用的需要继承RecursiveTask
而RecursiveTask 继承了ForkJoinTask
1.具体代码ForkJoin应用
package JUC;
import java.util.concurrent.RecursiveTask;
/**
* 求和计算的任务!
* 3000 6000(ForkJoin) 9000(Stream并行流)
* 1.ForkJoinPool 通过它来执行
* 2.计算任务 ForkJoinPool.execute(ForkJoinTask task)
* 3.计算类要继承ForkJoinTask
*/
public class ForkJoinTest extends RecursiveTask<Long>{
private static final long serialVersionUID = 1L;
private Long start;
private Long end;
//临界值
private Long tempLong = 10000L;
public ForkJoinTest() {
}
public ForkJoinTest(Long start, Long end) {
super();
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
Long iLong = null;
if ((end-start)<tempLong) {
Long sum = 0L;
for (int i = 0; i < 1000_0000; i++) {
sum += i;
}
System.out.println(sum);
}else {
//分支合并计算
//拆分压入
Long middle = (start+end)/2;
ForkJoinTest task1 = new ForkJoinTest(start,middle);
task1.fork();
ForkJoinTest task2 = new ForkJoinTest(middle+1,end);
task2.fork();
//获取结果
iLong = task1.join()+task2.join();
}
return iLong;
}
}
2.测试类
2.1测试1和结果
//3000程序员
@Test
public void test1() {
Long startTime = System.currentTimeMillis();
Long sum = 0L;
for (Long i = 1L; i < 100000000; i++) {
sum += i;
}
System.out.println(sum);
Long endTime = System.currentTimeMillis();
System.out.println("sum="+sum+"时间:"+(endTime-startTime));
}
2.2测试2和结果
//8000程序员
@Test
public void test2() {
Long startTime = System.currentTimeMillis();
//先获取ForkJoinPool池子
ForkJoinPool forkJoinPool = new ForkJoinPool();
//我具体使用定义的对象
ForkJoinTest forkJoinTest = new ForkJoinTest(0L,100000000L);
//提交任务
ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinTest);
try {
//获取提交结果
Long sum = submit.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
Long endTime = System.currentTimeMillis();
System.out.println("sum="+"时间:"+(endTime-startTime));
}
是分的核数越多?线程越多所以慢了? 由于我机子性能不行 直接出不来
2.3测试3和结果
//12000程序员
@Test
public void test3() {
Long startTime = System.currentTimeMillis();
//Stream并行流
LongStream.rangeClosed(0L, 100000000L)
.parallel()
.reduce(0,Long::sum);
Long endTime = System.currentTimeMillis();
System.out.println("sum="+"时间:"+(endTime-startTime));
}
可见最快的是Stream并行流