高并发压力测试

高并发压力测试

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

    }
}
相关推荐
while(1){yan}3 小时前
网络协议TCP
java·网络·网络协议·tcp/ip·青少年编程·电脑常识
一过菜只因3 小时前
JavaWeb后端(spring--boot)
java·开发语言
五仁火烧3 小时前
安装rust开发环境
开发语言·后端·rust
yuyu_03043 小时前
SOHE智能厨余垃圾处理系统
java·vue
IT枫斗者3 小时前
Netty的原理和springboot项目整合
java·spring boot·后端·sql·科技·mysql·spring
Yue丶越3 小时前
【C语言】动态内存管理
c语言·开发语言
Edward111111113 小时前
普通java项目转为maven项目 J文件后缀.java变C文件
java·开发语言·maven
赵谨言3 小时前
基于OpenCV的图像梯度与边缘检测研究
大数据·开发语言·经验分享·python
一雨方知深秋3 小时前
二.java程序基本语法
java·类型转换·变量·方法·运算符·字面量·关键字标识符
Java程序之猿3 小时前
Springboot 集成apache-camel +mqtt 根据主题处理mqtt消息
java·spring boot·后端