Java8新特性之并行流与串行流

Java8新特性之并行流与串行流


前言:
Java8新特性之并行流与串行流
并行流与顺序流
了解 Fork/Join框架
Fork/Join 框架与传统线程池的区别

1、ForkJoinCalculateTest

package com.chenheng;

import com.chenheng.java8.ForkJoinCalculate;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;

/**
 * @author chenheng
 * @date 2021/11/14 21:19
 */
@SpringBootTest
public class ForkJoinCalculateTest {
    @Test
    void test01(){
        Instant start = Instant.now();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinCalculate task = new ForkJoinCalculate(0, 10000000000L);
        Long sum = pool.invoke(task);
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
    }
    @Test
    void test02(){
        Instant start = Instant.now();
        long sum = 0;
        for (long i = 0; i < 10000000000L; i++) {
            sum += i;
        }
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
    }
    @Test
    void test03(){
        Instant start = Instant.now();
        long sum = LongStream.rangeClosed(0, 10000000000L)
                .parallel()
                .reduce(0, Long::sum);
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗费时间为:" + Duration.between(start, end).toMillis());
    }
}

2、ForkJoinCalculate类

package com.chenheng.java8;

import java.util.concurrent.RecursiveTask;

/**
 * @author chenheng
 * @date 2021/11/14 21:07
 */
public class ForkJoinCalculate extends RecursiveTask<Long> {
    private static final long serialVersionUID = 12432143423L;
    private long start;
    private long end;
    private static final long THRESHOLD = 10000;

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

    @Override
    protected Long compute() {
        long length = end - start;
        if (length <= THRESHOLD) {
            long sum = 0;
            for (long i = start; 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();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值