Java Web框架 压力测试 栅栏 CyclicBarrier

Java Web框架 压力测试 栅栏 CyclicBarrier

package mvc.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 压力测试
public class StressTest {

  public static void main(String[] args) {
    
    // 并发线程数
    int count = 5;
    // 创建一个线程池
    ExecutorService exec = Executors.newCachedThreadPool();
    // 创建栅栏
    CyclicBarrier cb = new CyclicBarrier(count);
    
    // 模拟客户端访问
    for (int i = 1; i <= count; i++) {
      final int NO = i;
      Runnable run = new Runnable() {
        public void run() {
          try {
            // 等待
            cb.await();
            System.out.println("Thread:" + NO);
            String url_action = "http://localhost:8080/api/user_edit?user_id=" + String.valueOf(NO);
            System.out.println(url_action);
            
            URL url = new URL(url_action);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            String result = "";
            while ((line = in.readLine()) != null) {
              result += line;
            }
            
            System.out.println("第:" + NO + " 个");
            System.out.println(result);
                        
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      };
      
      // 执行任务
      exec.execute(run);
    }
                // 关闭线程池
    exec.shutdown();
  }

}

 

发表回复

您的电子邮箱地址不会被公开。