ForkJoin

分支合并

什么是ForkJoin

ForkJoin在jdk1.7发行,并行执行任务,提高效率,适用于大数据量!
大数据:MapReduce(把大任务拆分为小任务)

ForkJoin特点:工作窃取

这个里面维护的都是双端队列

ForkJoin使用


计算类

/*
求个计算的任务!
3000 6000(ForkJoin) 9000(Stream并行流)

如何使用ForkJoin
1.ForkJoinPool 通过它来执行
2.计算任务 ForkJoinPool.execute(ForkJoinTask<?> task)
3.计算类要继承 ForkJoinTask
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;//1
    private Long end;//1000000000

    // 临界值
    private Long temp = 10000L;

    public ForkJoinDemo(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 {//ForkJoin 递归
            // 分支合并计算
            Long middle = (start + end) / 2;//中间值
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork();//拆分任务,把任务压入线程队列
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
            task2.fork();//拆分任务,把任务压入线程队列

            return task1.join() + task2.join();

        }
    }
}

测试类

/*
同一个任务,别人效率高你几十倍!
 */
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        test1();//sum=500000000500000000 时间:12904
//        test2();//sum=500000000500000000 时间:9484
        test3();//sum=500000000500000000 时间:193

    }

    // 普通程序员
    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
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);//提交

        Long sum = submit.get();

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

    // nb
    public static void test3() {
        long start = System.currentTimeMillis();

        // Stream并行流 () (]
        long sum = LongStream
                .rangeClosed(0L, 10_0000_0000L)
                .parallel()
                .reduce(0, Long::sum);

        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + " 时间:" + (end - start));
    }
}
posted @   不写代码想写诗的虫子  阅读(85)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示