并发工具类闭锁CountDownLatch练习

文章摘自【java并发编程实战】

1. 闭锁的作用相当于一扇门:在闭锁状态到达结束状态之前,这扇门一直是关闭着的,并且没有任何线程能够通过,当到达结束状态时,这扇门会打开并允许所有的线程通过。
2. 当闭锁到达结束状态,将不会再改变状态,因此这扇门将永远保持打开状态。

/**
	 * 统计所有线程执行完后所花费的时间
	 * @param nThreads 线程数
	 * @param task 任务
	 * @return 执行时间
	 * @throws InterruptedException
	 */
	public long timeTasks(int nThreads,final Runnable task) throws InterruptedException{
		final CountDownLatch startGate = new CountDownLatch(1);
		final CountDownLatch endGate = new CountDownLatch(nThreads);
		
		for(int i=0;i<nThreads;i++){
			Thread t = new Thread(){
				public void run(){
					try{
						startGate.await();
						try{
							task.run();
						}finally{
							endGate.countDown();
						}
					}catch(InterruptedException ignored){}
				}
			};
			t.start();
		}
		
		long start = System.nanoTime();
		startGate.countDown();
		endGate.await();
		long end = System.nanoTime();
		return end - start;
	}

猜你喜欢

转载自elena-me.iteye.com/blog/2286609