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

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

相关推荐
2402_8575893616 分钟前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰40 分钟前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer40 分钟前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
IT良41 分钟前
c#增删改查 (数据操作的基础)
开发语言·c#
哎呦没1 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
Kalika0-02 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch2 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
编程、小哥哥2 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
代码雕刻家2 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技2 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm