并行执行任务,提高效率。把大任务拆分城小任务。分开执行,最后结果汇总。
特点
:工作窃取
维护的是 双端队列
,
package forkjoin;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
/**
* @author admin
* @version 1.0.0
* @ClassName Test.java
* @Description TODO
* @createTime 2021年06月01日 19:31:00
*/
public class Test {
public static void main(String[] args) throws Exception{
test1();
test2();
test3();
}
public static void test1(){
long sum = 0;
long start = System.currentTimeMillis();
for (int i = 0; i <= 1000000000; i++) {
sum = sum + i;
}
long end = System.currentTimeMillis();
System.out.println("sum"+sum+" 时间"+(end-start));
}
public static void test2()throws Exception{
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new demo1(0,1000000000);
ForkJoinTask<Long> submit = forkJoinPool.submit(task);
long end = System.currentTimeMillis();
System.out.println("sum"+submit.get()+"时间"+(end-start));
}
public static void test3(){
long start = System.currentTimeMillis();
long sum = LongStream.rangeClosed(0,1000000000).parallel().reduce(0,Long::sum);
long end = System.currentTimeMillis();
System.out.println("sum"+sum+"时间"+(end-start));
}
}
package forkjoin;
import java.util.concurrent.RecursiveTask;
/**
* @author admin
* @version 1.0.0
* @ClassName demo1.java
* @Description TODO
* @createTime 2021年06月01日 19:14:00
*/
public class demo1 extends RecursiveTask<Long> {
private long start;
private long end;
// 临界值
private long temp = 10000L;
public demo1(long start, long end) {
this.start = start;
this.end = end;
}
// 计算方法
@Override
protected Long compute() {
if ((end-start)<temp){
long sum = 0;
for (long i = start;i<=end;i++){
sum = sum + i;
}
return sum;
}else
{
long middle = (start+end)/2; // 中间值
demo1 task1 = new demo1(start,middle);
task1.fork(); // 拆分任务,把任务压入线程队列
demo1 task2 = new demo1(middle+1,end);
task2.fork();
return task1.join()+task2.join();
}
}
}