java基础7

java基础7

package kuangstudy.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

public class Test01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();//计算用时:6838
        test2();//耗时:3866
        test3();//计算用时:108
    }

    //测试直接执行
    public static void test1(){
        Long sum=0L;
        long start=System.currentTimeMillis();
        for (Long i = 1L; i <= 10_0000_0000L; i++) {
            sum+=i;
        }
        long end=System.currentTimeMillis();
        System.out.println("sum1="+sum+"计算用时:"+(end-start));
    }

    //测试forkjoin的执行效率
    public static void test2() throws ExecutionException, InterruptedException {

        long start=System.currentTimeMillis();
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        System.out.println("sum2="+forkJoinPool.submit(new Fork(0L, 10_0000_0000L)).get());
        long end=System.currentTimeMillis();
        System.out.println("耗时:"+(end-start));
    }

    //测试流式计算
    public static void test3(){
        long start=System.currentTimeMillis();
        long sum= LongStream.rangeClosed(0L,10_0000_0000L).parallel().reduce(0,Long::sum);
        long end=System.currentTimeMillis();
        System.out.println("sum3="+sum+"计算用时:"+(end-start));
    }
}

class Fork extends RecursiveTask<Long>{
    private long start;
    private long end;
    private long temp=10000L;

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

    @Override
    protected Long compute() {
        if ((end-start)<temp){
            Long sum=0L;
            for (long i = start; i <= end; i++) {
                sum+=i;
            }
            return sum;
        }
        else {
            long middle = (start + end) / 2;
            Fork fork1 = new Fork(start, middle);
            fork1.fork();
            Fork fork2 = new Fork( middle+1,end);
            fork2.fork();
            return fork1.join()+fork2.join();
        }
    }
}

执行结果:

sum1=500000000500000000计算用时:6838
sum2=500000000500000000
耗时:3866
sum3=500000000500000000计算用时:108

Process finished with exit code 0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值