高并发压力测试

高并发压力测试

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

    }
}
相关推荐
阿珊和她的猫3 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
fouryears_234175 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~6 小时前
C#---StopWatch类
开发语言·c#
桦说编程7 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
lifallen7 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研7 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
没有bug.的程序员8 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋8 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
cui__OaO9 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
阿华的代码王国9 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端