CountDownLatch的使用
应用场景:适用于需要等待某个条件达到要求后才能做后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操作。例(游戏中需要等待五个人同时就续后才能开始)
// 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。 public static void main(String[] args) throws InterruptedException { // 开始的倒数锁 final CountDownLatch begin = new CountDownLatch(1); // 结束的倒数锁 final CountDownLatch end = new CountDownLatch(5); // 十个线程相当于十个选手 final ExecutorService exec = Executors.newFixedThreadPool(5); for (int index = 0; index < 5; index++) { final int NO = index + 1; Runnable run = new Runnable() { public void run() { try { // 如果当前计数为零,则此方法立即返回。 begin.await(); Thread.sleep((long) (Math.random() * 10000)); System.out.println("No." + NO + " arrived"); } catch (InterruptedException e) { } finally { // 每个选手到达终点时,end就减一 end.countDown(); } } }; exec.submit(run); } System.out.println("Game Start……"); // begin减一,开始游戏 begin.countDown(); // 等待end变为0,即所有选手到达终点 end.await(); System.out.println("Game Ove……"); exec.shutdown(); }