并行流和线程的配合使用

测试得出main线程配合一个线程使用时,耗时较低,当多个线程进行计算时,线程内计算及其耗时。
PS:条件有限,只在单台电脑上进行了测试。

public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 3, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        // 倒计时锁存器
        CountDownLatch latch = new CountDownLatch(1);
        try {
            long a1 = System.currentTimeMillis();

            Future<Long> submit1 = threadPoolExecutor.submit(() -> {
                Long reduce = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0L, Long::sum);
                latch.countDown();
                long a2 = System.currentTimeMillis();
                System.out.println("耗时(线程):"+(a2-a1));
                return reduce;
            });

            // 主线程
            long a3 = System.currentTimeMillis();
            Long reduce1 = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0L, Long::sum);
            System.out.println(reduce1);
            long a4 = System.currentTimeMillis();
            System.out.println("耗时(主):"+(a4-a3));

            // 线程等待
            latch.await();
            long sum = submit1.get()+reduce1;
            System.out.println(sum+"耗时(总):"+(a4-a1));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
    }
主线程+单个线程结果:
耗时(线程):418
耗时():326
1000000001000000000耗时():427
主线程+多个线程结果:
耗时():397
耗时(线程):1999
耗时(线程):2057
1000000001000000000耗时():2057
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值