ForkJoin详解

1.分支合并 (大数据量的去使用)

ForkJoin详解_第1张图片ForkJoin详解_第2张图片

ForkJoin详解_第3张图片 

package com.kuang.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.function.LongBinaryOperator;
import java.util.stream.LongStream;

/**
 * 程序员分3000 6000(forkjoin) 9000(Stream 并行流) 等
 */
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {


//        test1();11705ms

//        test2();7077ms
        
        test3();//207ms
    }

    //普通程序员  11705
    public static void test1(){
        long start = System.currentTimeMillis();

        Long sum=0L;
        for (Long i = 1L; i < 10_0000_0000; i++) {
            sum+=i;
        }

        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"时间:"+(end-start));
    }

    //会使用ForkJoin的  7077
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask task = new ForkJoinDemo(0l, 10_0000_0000l);

        ForkJoinTask submit = forkJoinPool.submit(task);//提交任务

        Long sum = submit.get();
        //forkJoinPool.execute(task);
//        Long aLong = task.get();//拿到返回值


        long end = System.currentTimeMillis();
        System.out.println("sum="+sum+"时间:"+(end-start));
    }



    //Steam并行流
    public static void test3(){
        long start = System.currentTimeMillis();
     //range() (]
        long reduce = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        //1+到1000000000L

        long end = System.currentTimeMillis();
        System.out.println("sum="+reduce+"时间:"+(end-start));
    }


}

你可能感兴趣的:(JUC,java,开发语言)