JUC —— ForkJoin

ForkJoin

ForkJoin(分之合并)在JDK1.7出现的,并行执行任务,提高效率,大数据量!
大数据:M安排Reduce(把大任务拆分为小人物)

特点:

工作窃取:有两个线程池在执行任务,A线程池执行完任务后发现B线程池还没执行完,A线程池就会将B线程池中等待的线程任务拿到自己的池中执行

操作

/**
 * 求和计算
 * 使用ForkJoin
 * 1.forkJoinPool 通过它来执行
 * 2.计算任务 forkJoinPool.execute(ForkJoinTask task)
 * 3.计算类要继承RecursiveTask
 */
public class ForkJoinTest extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    //临界值
    private Long temp = 10000L;

    public ForkJoinTest(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{
            //中间值
            Long middle = (start + end) / 2;
            ForkJoinTest forkJoinTest1 = new ForkJoinTest(start, middle);
            forkJoinTest1.fork(); //拆分任务,把任务压入线程队列
            ForkJoinTest forkJoinTest2 = new ForkJoinTest(middle,end);
            forkJoinTest2.fork();
            return forkJoinTest1.join() + forkJoinTest2.join();
        }
    }
}
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();
        test2();
        test3();
    }
    //普通
    public static void test1(){
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for(Long i=1L;i<=10_0000_0000L;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> submit = forkJoinPool.submit(new ForkJoinTest(0L, 10_0000_0000L));
        Long sum = submit.get();
        long end = System.currentTimeMillis();
        System.out.println("ForkJoin获取sum=+"+sum+"时间"+(end-start));
    }
    public static void test3(){
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("Stream并行流获取sum=+"+sum+"时间"+(end-start));
    }
}

执行结果:

普通获取sum=+500000000500000000时间6638
ForkJoin获取sum=+500065535999828224时间4535
Stream并行流获取sum=+500000000500000000时间287

可以看出ForkJoin确实比普通的查询要快一些,并且它通过设置临界值,是可调节的,可优化的。
同时也对比出Stream的强大。

你可能感兴趣的:(JUC,juc)