1 import java.util.concurrent.CountDownLatch; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 5 /** 6 * 16.Java5的CountDownLatch同步工具 7 * 犹如倒计时计数器,调用CountDownLatch对象的CountDown方法就将计数器减1, 8 * 当计数到达0事,则所有等待者或单个等待着开始执行。 9 * 10 * @author LiTaiQing11 *12 */13 public class CountdownLatchTest {14 15 public static void main(String[] args) {16 ExecutorService service = Executors.newCachedThreadPool();17 final CountDownLatch cdOrder = new CountDownLatch(1);18 final CountDownLatch cdAnswer = new CountDownLatch(3);19 for (int i = 0; i < 3; i++) {20 Runnable runnable = new Runnable() {21 public void run() {22 try {23 System.out.println("线程"24 + Thread.currentThread().getName() + "正准备接受命令");25 cdOrder.await();26 System.out.println("线程"27 + Thread.currentThread().getName() + "已接受命令");28 Thread.sleep((long) (Math.random() * 10000));29 System.out30 .println("线程"31 + Thread.currentThread().getName()32 + "回应命令处理结果");33 cdAnswer.countDown();34 } catch (Exception e) {35 e.printStackTrace();36 }37 }38 };39 service.execute(runnable);40 }41 try {42 Thread.sleep((long) (Math.random() * 10000));43 44 System.out.println("线程" + Thread.currentThread().getName()45 + "即将发布命令");46 cdOrder.countDown();47 System.out.println("线程" + Thread.currentThread().getName()48 + "已发送命令,正在等待结果");49 cdAnswer.await();50 System.out.println("线程" + Thread.currentThread().getName()51 + "已收到所有响应结果");52 } catch (Exception e) {53 e.printStackTrace();54 }55 service.shutdown();56 57 }58 }