CountDownLatch 使用,计算多个异步线程所使用时间

1. 计算Runnable 接口在主线程运行时间

public class Main20200328 {

    public static void main(String[] args) {
		long start= System.currentTimeMillis();
	MyRunable myRunable=new MyRunable();
	for (int i = 0; i < 5; i++) {
       myRunable.run();
	}
		long end= System.currentTimeMillis();
		System.out.println("计算MyRunable耗费时间:"+(end-start));
	}
  }
  class MyRunable implements Runnable{

	@Override
	public void run() {
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 System.out.println("直接调用Runnable 是在主线程中执行....");
	}
	  
}

2. 使用 CountDownLatch 计算子线程 异步线程运行时间

public class Main20200328 {
	 // 闭锁,用于计算10个线程运行时间
	 // 概念: 在完成某些 运算时,  只有其他线程的运算全部完毕,当前运行才继续执行
	 
	 public static void main(String[] args) {
		long start= System.currentTimeMillis(); 
		// 5 是计数器
		CountDownLatch Latch=new CountDownLatch(5);
		LatchDemo latchDemo=new LatchDemo(Latch);
		// 无法用开始时间,结束时间来计算
	for (int i = 0; i < 5; i++) {
        	new Thread(latchDemo).start();
	}
	try {
		Latch.await();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	long end= System.currentTimeMillis(); 	
		
	System.out.println("5个线程运行时间是:"+(end-start));
    }
	
	static class LatchDemo implements Runnable{
			
			private CountDownLatch latch;
			public LatchDemo(CountDownLatch latch) {
				super();
				this.latch = latch;
			}
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					// 5个计数器,每个线程执行完毕以后-1
					latch.countDown();
		         }
			}
		  }
	  
}
发布了111 篇原创文章 · 获赞 123 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/dreams_deng/article/details/105156525