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

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

相关推荐
代码小将1 小时前
Leetcode209做题笔记
java·笔记·算法
专注_每天进步一点点1 小时前
idea 启动Springboot项目在编译阶段报错:java: OutOfMemoryError: insufficient memory
java·spring boot·intellij-idea
dhxhsgrx2 小时前
PYTHON训练营DAY25
java·开发语言·python
不知几秋3 小时前
数字取证-内存取证(volatility)
java·linux·前端
风逸hhh5 小时前
python打卡day25@浙大疏锦行
开发语言·python
刚入门的大一新生5 小时前
C++初阶-string类的模拟实现与改进
开发语言·c++
chxii6 小时前
5java集合框架
java·开发语言
老衲有点帅6 小时前
C#多线程Thread
开发语言·c#
C++ 老炮儿的技术栈6 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法