Fork-join框架

Fork-join框架

forkjoin特点:工作密取,平衡可用线程的工作负载。分支并行

每个工作线程都有一个双端队列 (一个工作线程将子任务压入其双端队列队头,一个工作线程空闲时,它会从另一个双端队列的队尾“密取”一个任务)

主要用于大数据下的计算

复制代码
package com.wfy.ForkJoin;
import java.util.concurrent.RecursiveTask;
//求和计算
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;
    private Long end;
​
​
    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }
    //分支计算方法
    @Override
    protected Long compute() {
        Long temp = 10000L;
        if ((end - start) < temp) {
            Long num = 0L;
            for (Long i = start; i < end; i++) {
                num += i;
            }
            return num;
        } else {
            //forkjoin
            long middle = (end - start) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork();//拆分任务,将任务压入线程
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
            task2.fork();//拆分任务,将任务压入线程
            return  task1.join()+ task2.join();
        }
    }
}
复制代码

 

测试方法

复制代码
package com.wfy.ForkJoin;
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 {
        //普通方法
       // test01();
        //forkjoin方法
        //test02();
        test03();
    }
    //普通方法
    public static  void test01(){
        Long sum=0L;
        long start = System.currentTimeMillis();
        for (int i = 0; i <=10_0000_0000 ; i++) {
                     sum+=i;
        }
        long end=  System.currentTimeMillis();
        System.out.println("sum= "+sum+"\t"+"时间="+(end-start));
    }
    //forkJoin方法
    public static  void test02() 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+"\t"+"时间="+(end-start));
    }
​
     //Stream并行流
    public static void test03(){
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0, 10_0000_0000).parallel().reduce(0, Long::sum);
        long end=  System.currentTimeMillis();
        System.out.println("sum= "+sum+"\t"+"时间="+(end-start));
    }
}
复制代码
 
posted @   ShamUnite  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示