java多线程同步工具之CountDownlatch

CountDownLatch犹如一个计数器,调用CountDownLatch对象的countDown()方法将计数器减一,当计数器到达0时,则所有等待者或单个等待者就开始执行,就好比:裁判一声令下,运动员同时开始奔跑,或者所有运动员都跑到了终点后裁判才可以公布结果。


案例:

public class CountdownLatchTest {

	public static void main(String[] args) {
		
		/*创建一个缓存型线程池*/
		ExecutorService service = Executors.newCachedThreadPool();
		
		/*创建一个计数器只有一个数*/
		final CountDownLatch cdOrder = new CountDownLatch(1);
		/*创建一个计数器,有3个计数器*/
		final CountDownLatch cdAnswer = new CountDownLatch(3);
		
		/*循环模拟3个线程*/
		for (int i = 0; i < 3; i++) {
			Runnable runnable = new Runnable() {
				
				public void run() {
					try {
						
						System.out.println("线程" + Thread.currentThread().getName() + "正准备接受命令");
						/*等待*/
						cdOrder.await();
						
						System.out.println("线程" + Thread.currentThread().getName() + "已接受命令");
						/*休眠*/
						Thread.sleep((long) (Math.random() * 10000));
						
						System.out.println("线程" + Thread.currentThread().getName() + "回应命令处理结果");
						/*计数器减一*/
						cdAnswer.countDown();
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			service.execute(runnable);
		}
		try {
			/*休眠*/
			Thread.sleep((long) (Math.random() * 10000));

			System.out.println("线程" + Thread.currentThread().getName() + "即将发布命令");
			/*计数器减一*/
			cdOrder.countDown();
			
			System.out.println("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果");
			cdAnswer.await();
			
			System.out.println("线程" + Thread.currentThread().getName() + "已收到所有响应结果");
		} catch (Exception e) {
			e.printStackTrace();
		}
		service.shutdown();

	}
}

程序运行结果:


你可能感兴趣的:(多线程,CountDownLatch,计数器)