高并发压力测试

高并发压力测试

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());

    }
}
相关推荐
Java&Develop4 分钟前
springboot + mysql8降低版本到 mysql5.7
java·spring boot·后端
sg_knight7 分钟前
从单体架构到微服务:架构演进之路
java·spring boot·spring·spring cloud·微服务·云原生·架构
夜晚中的人海7 分钟前
【C语言】初阶数据结构相关习题(二)
c语言·开发语言·数据结构
武昌库里写JAVA21 分钟前
MacOS Python3安装
java·开发语言·spring boot·学习·课程设计
Dxy123931021623 分钟前
python如何设置excel单元格边框样式
开发语言·python·excel
eternal__day28 分钟前
Spring Cloud:构建云原生微服务架构的最佳工具和实践
java·spring cloud·微服务·云原生·架构
cdut_suye28 分钟前
【Linux系统】从 C 语言文件操作到系统调用的核心原理
java·linux·数据结构·c++·人工智能·机器学习·云计算
forestsea35 分钟前
Maven 插件参数注入与Mojo开发详解
java·maven·mojo
chaodaibing40 分钟前
Python解析Excel入库如何做到行的拆分
开发语言·python·excel
荔枝吻1 小时前
【抽丝剥茧知识讲解】引入mybtis-plus后,mapper实现方式
java·sql·mybatis