首页 > 代码库 > 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(); } } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。