Fork-join框架
forkjoin特点:工作密取,平衡可用线程的工作负载。
分支并行
每个工作线程都有一个
双端队列
(一个工作线程将子任务压入其双端队列队头,一个工作线程空闲时,它会从另一个双端队列的队尾“密取”一个任务)
主要用于大数据下的计算
package com.wfy.ForkJoin;
import java.util.concurrent.RecursiveTask;
//求和计算
public class ForkJoinDemo extends RecursiveTask<Long> {
private Long start;
private Long end;
public ForkJoinDemo(long start, long end) {
this.start = start;
this.end = end;
}
//分支计算方法
@Override
protected Long compute() {
Long temp = 10000L;
if ((end - start) < temp) {
Long num = 0L;
for (Long i = start; i < end; i++) {
num += i;
}
return num;
} else {
//forkjoin
long middle = (end - start) / 2;
ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
task1.fork();//拆分任务,将任务压入线程
ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
task2.fork();//拆分任务,将任务压入线程
return task1.join()+ task2.join();
}
}
}
测试方法
package com.wfy.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 {
//普通方法
// test01();
//forkjoin方法
//test02();
test03();
}
//普通方法
public static void test01(){
Long sum=0L;
long start = System.currentTimeMillis();
for (int i = 0; i <=10_0000_0000 ; i++) {
sum+=i;
}
long end= System.currentTimeMillis();
System.out.println("sum= "+sum+"\t"+"时间="+(end-start));
}
//forkJoin方法
public static void test02() 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+"\t"+"时间="+(end-start));
}
//Stream并行流
public static void test03(){
long start = System.currentTimeMillis();
long sum = LongStream.rangeClosed(0, 10_0000_0000).parallel().reduce(0, Long::sum);
long end= System.currentTimeMillis();
System.out.println("sum= "+sum+"\t"+"时间="+(end-start));
}
}
标签:Fork,end,框架,sum,Long,start,线程,long,join
From: https://www.cnblogs.com/wfy-studying/p/16811711.html