多线程学习7--CountDownLatch

CountDownLatch 倒计时器效果,线程在await处停下,当countDown

为0时就通行

下面模拟一生令下,三条线程开始执行,等三条线程都执行完之后,然后在进行下一阶段操作

package com.condition;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {
	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newCachedThreadPool();
		final CountDownLatch cdOrder = new CountDownLatch(1);
		final CountDownLatch cdCountDown = new CountDownLatch(3);
		for(int i = 0;i < 3;i++){
			Runnable runnable = new Runnable(){
				    @Override
					public void run() {
				    	System.out.println(Thread.currentThread().getName()
								+" 准备接受命令 ");
				    	try {
							cdOrder.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				    	System.out.println(Thread.currentThread().getName()
								+" 正在执行命令 ");
				    	try {
							Thread.sleep((long) (Math.random()*1000));
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				    	System.out.println(Thread.currentThread().getName()
								+" 正在回应 ");
				    	cdCountDown.countDown();
				    }
			};
			 threadPool.execute(runnable);
		}	
		try {
			Thread.sleep((long) (Math.random()*1000));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		synchronized(threadPool){
			System.out.println(Thread.currentThread().getName()
					+" 即将发布命令 ");
			cdOrder.countDown();
			System.out.println(Thread.currentThread().getName()
					+" 正在发布命令 ");
		}
		try {
			cdCountDown.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()
				+" 收到所有结果 ");
	}

}

  

原文地址:https://www.cnblogs.com/hzmbbbb/p/4280300.html