CountDownLatch Thread 启动多个线程,并统计所有线程消耗的时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/luoww1/article/details/53126932

  模拟启动3000 个线程,同时并发执行并统计所有线程执行完成后所消耗的时间。

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

public class ThreadHttps {

	public static void main(String[] args) {
		
		try {
			long start = System.currentTimeMillis();
			CountDownLatch startlatch=new CountDownLatch(300);//需要等待启动多少个线程  
			CountDownLatch endlatch=new CountDownLatch(300);//需要等待多少个线程完成后
	        for(int i =0;i<300;i++){
	        	Map<String, String> map = new HashMap<String, String>();
	        	//启动俩个线程,都去调用BS20102
	        	MyThread myThread1 = new MyThread(""+i,map,startlatch,endlatch);
	    		myThread1.start();
	    		startlatch.countDown();
	        }
	        endlatch.await();//等待所有工人完成工作  
	        long end = System.currentTimeMillis();
	        System.out.println("所有工作都完成消耗的时间:" + (end-start)+"毫秒"); 
		} catch (Exception e) {
			e.printStackTrace();
		} 

	}
	 public static class MyThread extends Thread{
			private String tradeType;
			private Map<String, String> map;
			private CountDownLatch startlatch;
			private CountDownLatch endlatch;
			public MyThread(String tradeType,Map<String, String> map, CountDownLatch startlatch,CountDownLatch endlatch){
				this.tradeType =tradeType;
				this.map = map;
				this.startlatch=startlatch;
				this.endlatch=endlatch;
			}
			public void run() {
				
				System.out.println("latch.getCount:" + startlatch.getCount());
										
				try {
					while(startlatch.getCount() != 0){
						
						Thread.sleep(10);
					}
					long start = System.currentTimeMillis();
					System.out.println("tradeType:" + tradeType + ",~~~开始执行~~~");
					Thread.sleep(3000);
					long end = System.currentTimeMillis();
					System.out.println("tradeType:" +tradeType+ " ,线程消耗时间" +(end-start));
					
					endlatch.countDown();//线程内容执行完成后,计数器减一
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
			}
		}
}


阅读更多
换一批

没有更多推荐了,返回首页