public class Test {
	
	//用于控制并发执行的个数
	private static CyclicBarrier barrier = null;
	//用于控制所有线程执行完成后计算平均值
	private static CountDownLatch countDownLatchTotal = null;
	//统计每次执行的时长
	private static Map<Integer, Long> map = new ConcurrentHashMap<>();
	//map的key的计算器,map的key也是线程的执行顺序
	private static AtomicInteger seq = new AtomicInteger(0);
	
	public static void doTest(String url,int totalRequesTimes,int concurrentTimes) throws Exception{
		barrier = new CyclicBarrier(concurrentTimes);
		countDownLatchTotal = new CountDownLatch(totalRequesTimes);
		
		ExecutorService executorService = Executors.newCachedThreadPool();
		
		for(int i=0;i<totalRequesTimes;i++){
			executorService.execute(() ->{
				try {
					Test.requestUrl(url);
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					countDownLatchTotal.countDown();
				}
			});
		}
		//所有线程执行完成后,计算响应时间
		countDownLatchTotal.await();
		count(totalRequesTimes);
	}
	
	public static void requestUrl(String url) throws Exception{
		barrier.await();
		long startTime = System.currentTimeMillis();
		Httpclient.doGet(url);
		long time = System.currentTimeMillis() - startTime;
		map.put(seq.incrementAndGet(), time);
	}
	
	public static void count(int totalRequesTimes){
		//累计执行时间
		long totalTimes = 0l;
		long total95Times = 0l;
		for(int i : map.keySet()){
			totalTimes += map.get(i);
			if(i<=95){
				total95Times += map.get(i);
			}
		}
		System.out.println("map中key的个数:"+map.keySet().size());
		System.out.println("平均响应时间:"+(totalTimes/1000)/totalRequesTimes);
		System.out.println("95%平均响应时间:"+(total95Times/1000)/(totalRequesTimes*95/100));
	}
	
	public static void main(String[] args) throws Exception{
		Test.doTest("https://www.baidu.com", 100, 10);
		
	}
}
评论