高并发压力测试

高并发压力测试

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

    }
}
相关推荐
CryptoRzz1 天前
欧美(美股、加拿大股票、墨西哥股票)股票数据接口文档
java·服务器·开发语言·数据库·区块链
杂货铺的小掌柜1 天前
apache poi excel 字体数量限制
java·excel·poi
Never_Satisfied1 天前
在JavaScript / HTML中,div容器在内容过多时不显示超出的部分
开发语言·javascript·html
大厂码农老A1 天前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
艾菜籽1 天前
Spring MVC入门补充2
java·spring·mvc
艾莉丝努力练剑1 天前
【C++STL :stack && queue (一) 】STL:stack与queue全解析|深入使用(附高频算法题详解)
linux·开发语言·数据结构·c++·算法
爆更小哇1 天前
统一功能处理
java·spring boot
程序员鱼皮1 天前
我造了个程序员练兵场,专治技术焦虑症!
java·计算机·程序员·编程·自学
胡萝卜3.01 天前
深入理解string底层:手写高效字符串类
开发语言·c++·学习·学习笔记·string类·string模拟实现
n8n1 天前
SpringAI 完全指南:为Java应用注入生成式AI能力
java·后端