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

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

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