编程语言
首页 > 编程语言> > Java如何快速计算百亿数值的累加

Java如何快速计算百亿数值的累加

作者:互联网

可以利用Java 1.8 新特性操作

public class ForkJoinCalculate extends RecursiveTask<Long> {

    private long start;
    private long end;
    private static  final  long  THRESHOLD= 10000L;

    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,length);
            right.fork();
            return left.join()+right.join();
        }
    }
}

现在开始测试

public class ForkJoinTest {
    @Test
    public void test(){
        Instant start = now();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0,1000000000L);
        Long sum = pool.invoke(task);
        Instant end = now();
        System.out.println("执行时间:"+ Duration.between(start,end).toMillis()+"毫秒  执行结果:"+sum);
    }
}

执行时间在这里插入图片描述

标签:ForkJoinCalculate,end,百亿,long,累加,start,private,Java,public
来源: https://blog.csdn.net/qq_42506755/article/details/95358499