其他分享
首页 > 其他分享> > ForkJoin

ForkJoin

作者:互联网

ForkJoin(工作窃取)

在大数据量的时候使用,提高效率。

大数据:Map Reduce(把大任务拆分成小任务)


例子:
//定义一个forkjoin操作类,继承于RecursiveTask(递归任务)

import java.util.concurrent.RecursiveTask;

//求和计算的任务
public class ForkJoinDemo extends RecursiveTask<Long> {
public static void main(String[] args) {

}
private long start;
private long end;
private long temp = 10000000;

public ForkJoinDemo(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 += i;
}
return sum;
}else{
long middle = (start + end) / 2;
ForkJoinDemo forkJoinDemo = new ForkJoinDemo(start, middle);
forkJoinDemo.fork();
ForkJoinDemo forkJoinDemo1 = new ForkJoinDemo(middle + 1, end);
forkJoinDemo1.fork();
return forkJoinDemo.join() + forkJoinDemo1.join();
}
}
}


//调用程序,三种方式
import java.util.concurrent.ExecutionException;
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 ExecutionException, InterruptedException {
test03();
}

public static final long maxEnd = 10_0000_0000;
//普通方法,最差
public static void test01(){
long start = System.currentTimeMillis();
long sum = 0;
for (int i = 1; i <= maxEnd; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println("结果:" + sum + ",耗时:" + (end - start));
}

//forkjoin方法,次优
public static void test02() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
long sum = 0;
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinDemo(0, maxEnd);
ForkJoinTask<Long> submit = forkJoinPool.submit(task);
sum = submit.get();
long end = System.currentTimeMillis();
System.out.println("结果:" + sum + ",耗时:" + (end - start));
forkJoinPool.shutdown();
}

//stream方法,并行流,最优
public static void test03(){
long start = System.currentTimeMillis();
long sum = 0;

long reduce = LongStream.rangeClosed(0, maxEnd).parallel().reduce(0, Long::sum);

long end = System.currentTimeMillis();
System.out.println("结果:" + reduce + ",耗时:" + (end - start));
}
}

标签:end,sum,System,long,start,ForkJoin,public
来源: https://www.cnblogs.com/gdstcymc/p/15103554.html