java CountDownLatch类的用法

CountDownLatch类中维护了一个计数器,当计数器为0时,释放所有线程。这个类可以用于当所有的资源都初始化后进行操作。

CountDownLatch中的await方法等待计数器达到0,表示所有的线程已经执行完毕。如果计数器不为0,await()方法会一直阻塞等待计数器变为0。而countDown()方法用于递减计数器。

下面是一个计算执行时间的例子:

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
	
	public static Long getMillions(){
		//相当于建立一个起跑线
		 final CountDownLatch startDownLatch = new CountDownLatch(1);
		 //10个线程执行完后释放
		 final  CountDownLatch endCountDownLatch = new CountDownLatch(10);
		 for(int i=0;i<10;i++){
			 Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						//等待startDownLatch中的技术器减到0
						startDownLatch.await();
						System.out.println(Thread.currentThread().getName());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}finally {
						//endCountDownLatch中的计数器减一
						endCountDownLatch.countDown();
					}
					
				}
			});
			 
			 thread.start();
		 }
		 Long startMillions = System.currentTimeMillis();
		 //所有线程开始执行
		 startDownLatch.countDown();
		
		 try {
			 //所有线程执行完后,当endCountDownLatch的计数器等于0时释放
			endCountDownLatch.await();
			System.out.println(System.currentTimeMillis()-startMillions);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		 return null;
	}
	
	public static void main(String[] args) {
		getMillions();
	}
}

猜你喜欢

转载自chen-sai-201607223902.iteye.com/blog/2373382