高并发压力测试

高并发压力测试

CountDownLatch就是JUC包下的一个工具,整个工具最核心的功能就是计数器。

需要一个并发安全的计数器来操作。CountDownLatch就可以实现。

给CountDownLatch设置一个数值。

每个业务处理完毕之后,执行一次countDown方法,指定的值每次在执行countDown方法时,对值进行-1。

主线程可以在业务处理时,执行await,主线程会阻塞等待任务处理完毕。

java 复制代码
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 高并发模拟压测
 * 需要设置线程数、每个线程执行次数、业务代码替换
 */

@Slf4j
public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        final AtomicInteger atomicInteger = new AtomicInteger(0);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(10);
        CountDownLatch countDownLatch2 = new CountDownLatch(10);
        //模拟10个线程并发
        for (int i = 0; i < 10; i++) {
            executorService.submit(()->{
                //阻塞线程,直到计数为0
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // start 并发执行业务,每个线程执行10次
                for (int j = 0; j < 10; j++) {
                    // 用业务代码替换
                    atomicInteger.incrementAndGet();
                }
                countDownLatch2.countDown();
                //end
            });
            //计数器减1
            countDownLatch.countDown();
        }
        //保证所有线程执行完
        countDownLatch2.await();
        executorService.shutdown();
        log.info("atomicInteger的值为:{}", atomicInteger.get());

    }
}
相关推荐
醇醛酸醚酮酯16 分钟前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt
jioulongzi21 分钟前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
我是一只代码狗24 分钟前
springboot中使用线程池
java·spring boot·后端
hello早上好37 分钟前
JDK 代理原理
java·spring boot·spring
PanZonghui42 分钟前
Centos项目部署之Java安装与配置
java·linux
向阳@向远方1 小时前
第二章 简单程序设计
开发语言·c++·算法
沉着的码农1 小时前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
Mr_Xuhhh1 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华2 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
好开心啊没烦恼2 小时前
Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
开发语言·python·数据挖掘·数据分析