java8新特性 ————-stream 的并行流操作

  • Post author:
  • Post category:java


如果对象没有的话,请看我的java8的分类

在说并行之前先了解一下,parallel() 的底层  fork-join 模式

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * create gl 
 **/
public class ForkJoinCalculate extends RecursiveTask<Long> {

    private long start;
    private long end;
    private static final long THRESHOLD = 1000000;

    public ForkJoinCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = start - end;
        //如果到了临界值
        if(length <= THRESHOLD){
            long sum = 0;
            for (int i = 0;i <= end;i++){
                sum +=i;
            }
            return sum;
        }else {
             long middle = (start + end)/2;  //一半一半的拆分
             ForkJoinCalculate left = new ForkJoinCalculate(start,middle);
             left.fork(); //拆分子任务,同时压入线程队列

             ForkJoinCalculate right = new ForkJoinCalculate(middle+1,end);
             right.fork();
             return left.join() + right.join();
        }
    }

    public static void main(String[] args) {

        // fork - join  框架,多线程执行
        Instant start = Instant.now();//开始时间

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> forkJoinTask = new ForkJoinCalculate(0,1000000000L); // 这个值越大,与传统循环比较耗时越小
        Long sum = forkJoinPool.invoke(forkJoinTask);
        System.out.println(sum);

        Instant end = Instant.now();//结束时间
        System.out.println(Duration.between(start,end).getSeconds()); // 秒   getNano()纳秒

    }
}

import java.util.stream.LongStream;

/**
 * create gl 
 **/
public class Test04 {



    public static void test1(){
        long reduce = LongStream.rangeClosed(0, 10000000000L)
                .parallel()
                .reduce(0, Long::sum);
        System.out.println(reduce);
    }


    public static void main(String[] args) {
        test1();
    }


}



版权声明:本文为qq_37838223原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。