首页 > 代码库 > Java线程测试高并发

Java线程测试高并发

package com.expai.utils;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.HttpURLConnection;import java.net.URL;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import org.apache.log4j.Logger;public class BingfaTest {    protected static final Logger LOG = Logger.getLogger(BingfaTest.class);    private static  BingfaTest binfaTest = new BingfaTest();     public static BingfaTest getInstance() {            return binfaTest;        }     //count为启动线程的个数,httpUrl为请求的url,para为需要传的参数     public void exeThread(int count,String httpUrl,String para){         CyclicBarrier cyclicBarrier = new CyclicBarrier(count);         ExecutorService executorService = Executors.newFixedThreadPool(count);         for (int i = 0; i < count; i++)              executorService.execute(new BingfaTest().new Task(cyclicBarrier,httpUrl,para));         //执行后不再执行新任务shutdown,         executorService.shutdown();         //当线程池的工作队列中的所有任务执行完毕,executorService.isTerminated()方法就会返回true。         while (!executorService.isTerminated()) {              try {                   Thread.sleep(10);              } catch (InterruptedException e) {                   e.printStackTrace();              }         }     }     public class Task implements Runnable {         private CyclicBarrier cyclicBarrier;         private String httpUrl;         private String para;         public Task(CyclicBarrier cyclicBarrier,String httpUrl,String para) {              this.cyclicBarrier = cyclicBarrier;              this.httpUrl=httpUrl;              this.para=para;         }         @Override         public void run() {              try {                   // 等待所有任务准备就绪                   cyclicBarrier.await();                   // 测试内容                   URL url =new URL(httpUrl+para);                   HttpURLConnection connection = (HttpURLConnection) url.openConnection();                    connection.setDoOutput(true);                     connection.setDoInput(true);                   //组织提交信息                   PrintWriter out = new PrintWriter(connection.getOutputStream());                   out.print(para);                   out.flush();                   //获得返回信息                   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));                   String line=null;                   //返回的参数拼接成字符串                   StringBuffer content = new StringBuffer();                   while((line=in.readLine())!=null){                       content.append(line);                   }                   in.close();                   LOG.info("返回数据====="+content.toString());              } catch (Exception e) {                   e.printStackTrace();              }         }    }}