JAVA实现压力测试

在Java中实现压力测试通常涉及到使用多线程来模拟并发操作。以下是一个简单的例子,使用Java的ExecutorServiceCallable来执行并发的任务,进行简单的压力测试。

package useful;

import java.time.LocalDateTime;

import java.util.Calendar;

import java.util.Random;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class PressTest {

// Java实现压力测试
static class StressTask implements Callable<Boolean> {
public Boolean call() throws Exception {
// 这里放置你的业务逻辑
// 例如:
// Thread.sleep(1000); // 模拟耗时操作
Thread.sleep(getRandomNumber());
return true;
}
}

public static void main(String[] args) throws Exception {

// int random = getRandomNumber();

// System.out.println(random);

// Thread.sleep(random);

LocalDateTime localDateTime = LocalDateTime.now();

// String b = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

System.out.println(localDateTime);

// System.out.println(Calendar.getInstance());

StressTest();

System.out.println(Calendar.getInstance());

LocalDateTime localDateTime1 = LocalDateTime.now();

// String b = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

System.out.println(localDateTime1);

System.out.println("Finish!!!!!");

}

public static int getRandomNumber() {

// 创建一个Random对象

Random random = new Random();

// 生成一个0到1之间的随机小数

double randomDouble = random.nextDouble();

return (int) (randomDouble *1000);

}

public static void getRandomBetween(int min, int max) {
Random random = new Random();
int randomInt = random.nextInt(max - min + 1) + min;
System.out.println("随机整数:" + randomInt);
}

public static void StressTest() throws Exception {

// 创建固定大小的线程池

ExecutorService executor = Executors.newFixedThreadPool(10); // 假设我们要10个并发线程

// 提交100个并发任务

int tasks = 100;

Future<Boolean>[] futures = new Future[tasks];

for (int i = 0; i < tasks; i++) {

futures[i] = executor.submit(new StressTask());

}

// 等待所有任务完成

for (Future<Boolean> future : futures) {

future.get(); // 这将阻塞直到任务完成

}

// 关闭线程池

executor.shutdown();

}

}

这个例子中,我们定义了一个StressTask类,它实现了Callable接口。call方法中可以放置你要测试的业务逻辑,例如数据库操作、网络请求等。在main方法中,我们创建了一个固定大小的线程池,并提交了100个并发任务。每个Future实例对应一个任务,通过调用future.get()方法,我们等待所有任务完成。最后,我们关闭线程池以结束测试。

要进行压力测试,你需要根据实际情况调整线程池的大小以及提交的任务数量。这个例子提供了一个基本框架,你可以根据需要添加额外的监控和报告功能。

相关推荐
JAVA学习通21 小时前
北京明光云振铎数据科技Java面经
java·开发语言·科技
贫民窟的勇敢爷们1 天前
SpringBoot整合AOP切面编程实战,实现日志统一记录+接口权限校验
java·spring boot·spring
jerryinwuhan1 天前
基于各城市站点流量的复合功能比较
开发语言·php
AC赳赳老秦1 天前
供应链专员提效:OpenClaw自动跟踪物流信息、更新库存数据,异常自动提醒
java·大数据·服务器·数据库·人工智能·自动化·openclaw
迈巴赫车主1 天前
Java基础:list、set、map一遍过
java·开发语言
灵犀学长1 天前
基于 Spring ThreadPoolTaskScheduler + CronTrigger 实现的动态定时任务调度系统
java·数据库·spring
南 阳1 天前
Python从入门到精通day66
开发语言·python
好家伙VCC1 天前
【无标题】
java
十八旬1 天前
快速安装ClaudeCode完整指南
开发语言·windows·python·claude
前进的李工1 天前
EXPLAIN输出格式全解析:JSON、TREE与可视化
开发语言·数据库·mysql·性能优化·explain