从名字可以看出,CountDownLatch是一个倒数计数的锁,
当倒数到0时触发事件,也就是开锁,其他人就可以进入了。
在一些应用场合中,需要等待某个条件达到要求后才能做后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操作。
CountDownLatch最重要的方法是countDown()和await(),前者主要是倒数一次,后者是等待倒数到0,如果没有到达0,就只有阻塞等待了。
下面的例子简单的说明了CountDownLatch的使用方法,模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。
- package com.eyesmore.concurrent;
-
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
-
- public class CountDownLatchDemo {
-
- private static final int PLAY_AMOUNT = 10;
-
- public static void main(String[] args) {
-
-
-
- CountDownLatch begin = new CountDownLatch(1);
-
-
-
- CountDownLatch end = new CountDownLatch(PLAY_AMOUNT);
- Player[] plays = new Player[PLAY_AMOUNT];
- for(int i = 0;i<PLAY_AMOUNT;i++) {
- plays[i] = new Player(i+1,begin,end);
- }
- ExecutorService exe = Executors.newFixedThreadPool(PLAY_AMOUNT);
- for(Player p : plays) {
- exe.execute(p);
- }
- System.out.println("比赛开始");
- begin.countDown();
- try {
- end.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- System.out.println("比赛结束");
- }
-
-
- exe.shutdown();
- }
-
- }
-
-
- class Player implements Runnable {
-
- private int id;
-
- private CountDownLatch begin;
-
- private CountDownLatch end;
-
- public Player(int id, CountDownLatch begin, CountDownLatch end) {
- super();
- this.id = id;
- this.begin = begin;
- this.end = end;
- }
-
- public void run() {
- try {
- begin.await();
- Thread.sleep((long)(Math.random()*100));
- System.out.println("Play "+id+" has arrived. ");
-
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- end.countDown();
- }
- }
- }