Forkjoin在JDK1.7之后,并行执行任务!提高效率。大数据量
Forkjoin特点:工作窃取
这个里边维护的是双端队列
Forkjoin操作
package org.example.forkjoin;
import java.util.concurrent.RecursiveTask;
/**
* 求和计算
*如何使用forkjoin
* 1.通过forkjoinPool通过它来执行
* 2.计算任务 forkjoinPool.execute(ForkJoinTask task)
* 3.计算类要继承 ForkJoinTask
*/
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 sum = 0L;
for (Long i = start; i <= end ; i++) {
sum+=i;
}
return sum;
}else{//forkjoin
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();
}
}
}
package org.example.forkjoin;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// test1();//11478
// test2();//3731
test3(); //416
}
public static void test1(){
Long sum = 0L;
long start = System.currentTimeMillis();
for (Long i = 1L; i <= 10_0000_0000 ; i++) {
sum+=i;
}
long end = System.currentTimeMillis();
System.out.println("sum="+sum+"时间: "+(end-start));
}
//用forkjoin
public static void test2() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long>task = new ForkJoinDemo(0L,10_0000_0000l);
ForkJoinTask<Long> submit = forkJoinPool.submit(task);
Long sum = submit.get();
long end = System.currentTimeMillis();
System.out.println("sum="+sum+"时间: "+(end-start));
}
//stream流
public static void test3(){
long start = System.currentTimeMillis();
//Stream并行流 () (]
long sum = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0, Long::sum);
long end = System.currentTimeMillis();
System.out.println("sum="+sum+"时间: "+(end-start));
}
}