• Java:Java多线程实现性能测试


    创建多线程和线程池

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
     
    //开启的线程数
    int threadSize = 100;  
    //创建线程池
    ExecutorService executorService = Executors.newFixedThreadPool(threadSize);
    //开始时间
    long start = System.currentTimeMillis();
    //让线程池中的每一个线程都开始工作
    for (int j = 0; j < threadSize; j++) {
        //执行线程
        executorService.execute(new TestPerformance(threadSize));
    }
    //等线程全部执行完后关闭线程池
    executorService.shutdown();
    executorService.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
    //结束时间
    long end = System.currentTimeMillis();
    
    System.out.println("测试次数:" + TestPerformance.atomicInteger.get());
    System.out.println("用时:" + (end - start));
    System.out.println("速度:" + TestPerformance.atomicInteger.get() * 1000 / (end - start) + "次/秒");

    具体逻辑

    package com.test.performance;
     
     
    import java.util.concurrent.atomic.AtomicInteger;
     
    /**
     * 测试性能.
     */
    public class TestPerformance implements Runnable {
     
        //每个线程的执行次数
        private int size;
     
        //记录多线程的总执行次数,保证高并发下的原子性
        public static AtomicInteger atomicInteger = new AtomicInteger(0);
     
        public TestPerformance(int size) {
            this.size = size;
        }
     
        @Override
        public void run() {
     
            int count = 0;
            while (count < size) {
                count++;
     
                atomicInteger.getAndIncrement();
     
                ///////////////
            //在此写入需要测试性能的代码块
            ///////////////
     
                System.out.println("线程ID与对应的执行次数:" + Thread.currentThread().getId() + "--->" + count);
            }
        }
    }

    文章转载至:https://blog.csdn.net/weixin_43192102/article/details/106195948

  • 相关阅读:
    mysql官网下载yum
    zookeeper和kafka的leader和follower
    查看目标端口是否被占用
    scala中的val,var和lazy
    scala的异常处理try catch
    Navicat总是提示主键不存在问题
    idea常用快捷键
    wiremock技术入门
    Liunx常用操作(11)-VI编辑器-末行模式命令
    Liunx常用操作(十)-VI编辑器-命令模式命令
  • 原文地址:https://www.cnblogs.com/nhdlb/p/12968935.html
Copyright © 2020-2023  润新知