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()方法,我们等待所有任务完成。最后,我们关闭线程池以结束测试。

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

相关推荐
咸鱼2.08 小时前
【java入门到放弃】Dubbo
java·开发语言·dubbo
JAVA面经实录91714 小时前
Java企业级工程化·终极完整版背诵手册(无遗漏、全覆盖、面试+落地通用)
java·开发语言·面试
周杰伦fans15 小时前
AutoCAD .NET 二次开发:深入理解 EntityJig 的工作原理与正确实现
开发语言·.net
许彰午16 小时前
CacheSQL(二):主从复制——OpLog 环形缓冲区与故障自动恢复
java·数据库·缓存
Bat U17 小时前
JavaEE|多线程初阶(七)
java·开发语言
谭欣辰17 小时前
C++ 排列组合完整指南
开发语言·c++·算法
foundbug99918 小时前
自适应滤除直达波干扰的MATLAB实现
开发语言·算法·matlab
XDH_CS18 小时前
MySQL 8.0 安装与 MySQL Workbench 使用全流程(超详细教程)
开发语言·数据库·mysql
小短腿的代码世界18 小时前
Qt实时盈亏计算深度解析:从持仓数据到动态盈亏展示
开发语言·qt