测试串行和并发执行速度

并发的目的是为了让程序运行的更快,但是,并不是启动更多的线程就能让程序最大限度的并发执行,下面这个例子就是证明并发一定快吗?

package com.itcorey.Thread;

import java.io.Serializable;

/**
 * @Classname concurrentTest
 * @Description 多线程一定快吗?
 * @Date 2020/5/21 18:32
 * @Created by corey
 */
public class concurrentTest {

    private static final long count = 10000;

    public static void main(String[] args) throws Exception {
        //并发
        concurrentcy();
        //串行
        Serial();
    }

    private static void concurrentcy() throws Exception {
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a += 5;
                }
            }
        });
        thread.start();
        ;
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        thread.join();
        System.out.println("concurrentcy==并发"+time+"ms,b="+b);
    }

    private static void Serial() {
        long start = System.currentTimeMillis();
        int a  = 0;
        for (long i = 0;i< count;i++){
            a+=5;
        }
        int b = 0;
        for (long i = 0;i<count;i++){
            b--;
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("Serial==串行:"+time+"ms,b"+b+",a="+a);
    }


}

首先执行的是1万次:
在这里插入图片描述
并发1s 串行0s ----->并发比串行慢

第二次 10万
在这里插入图片描述
串行2s 并发9s -----并发比串行慢

第三次 100万
在这里插入图片描述串行4s 并发12s -----并发比串行慢

第四次10000000万数据的时候
在这里插入图片描述
串行11s 并发14s -----并发比串行慢

第五次一亿次
在这里插入图片描述
串行72s 并发48s ----串行比并发差不多慢一倍

总结一下:当并发执行累加操作不超过百万次的时候,速度比串行化累计操作要慢,当上了亿级数据量后,就会快很多,这是因为线程有创建和上下文切换的开销

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值