如何使用 java 创建 50 个线程来向特定 URL 发出简单的 http get 请求?
我希望每个线程发出大约 100-1k 个请求。
是否可以保证所有这些线程同时连接?
我基本上想要类似于 Apache bench 的东西,但是是用 java 编写的,所以我可以在这个过程中学习一些 java。
所以输入是:
1. # of requests in total
2. # of threads to use
3. url to make a request with
更新 我想跟踪请求统计信息,即特定请求平均花费多长时间,我需要一个线程安全的全局集合吗?
最佳答案
这是一些(不完整的)代码:
public class Test {
private static int REQUESTS;
private static int NUM_THREADS;
private static String URL;
private static ArrayList<Statistic> result = new ArrayList<Statistic>();
private static class ThreadTask implements Runnable {
private int tid;
public ThreadTask(int tid) {
this.tid = tid;
}
@Override
public void run() {
Statistic stat = new Statistic();
for(int i = 0; i < REQUESTS; i++) {
// make request
// add results to stat
}
result.add(tid, stat); // no need to lock because each
// thread writes to a dedicated index
}
}
public static void main(String[] args) {
// take command line arguments
REQUESTS = Integer.parseInt(args[0]);
NUM_THREADS = Integer.parseInt(args[1]);
URL = args[2];
Thread[] threads = new Thread[NUM_THREADS];
// start threads
for(int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(new ThreadTask(i));
threads[i].start();
}
// wait for threads to finish
for(int i = 0; i < NUM_THREADS; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Class Statistic
是您定义的用于收集您想要的任何统计信息的东西。
当然,可以提出很多改进建议,这只是我在 5 分钟内写的。 :) 希望对您有所帮助。
关于java - 创建 50 个线程连接到服务器以进行负载测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8189480/