java - 创建 50 个线程连接到服务器以进行负载测试

标签 java multithreading

如何使用 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/

相关文章:

java - 当 JVM 停止线程时,为 java 用户线程调用清理方法

c++ - 将多个参数从函数传递到线程时出现问题

java - Spring SFTP读文件锁

java - 如何在 SSLContextBuilder.create().loadTrustMaterial 的 JUnit 测试中抛出异常?

java - 即使字符串采用 UTF-8 格式,电子邮件主题也会以 CP1252 编码设置

c - C中的多线程

java - 这个同步块(synchronized block)需要吗?

java - Android - Activity 中方法的单元测试

java - 如何使用 Play Framework 获取特定 Web 套接字端点上的 Actor 列表?

c++11 线程与 .Net 线程?