10.线程通信CountDownLatch

CountDownLatch
1.一个同步的辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个、多个线程去一直等待,用给定的计数、初始化“CountDownLatch”。
  由于调用 countDown()方法 ,所以在当前计算到达之前,await()方法会一直处于阻塞状态,之后会释放所有的等待线程,await()方法的所有
  后续调用都将立即返回调用。
  1. public class CountDownLatchTest {
  2. // 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。
  3. public static void main(String[] args) throws InterruptedException {
  4. // 开始的倒数锁
  5. final CountDownLatch begin = new CountDownLatch(1);
  6. // 结束的倒数锁
  7. final CountDownLatch end = new CountDownLatch(10);
  8. // 十名选手
  9. final ExecutorService exec = Executors.newFixedThreadPool(10);
  10. for (int index = 0; index < 10; index++) {
  11. final int NO = index + 1;
  12. Runnable run = new Runnable() {
  13. public void run() {
  14. try {
  15. // 如果当前计数为零,则此方法立即返回。
  16. // 等待
  17. begin.await();
  18. Thread.sleep((long) (Math.random() * 10000));
  19. System.out.println("No." + NO + " arrived");
  20. } catch (InterruptedException e) {
  21. } finally {
  22. // 每个选手到达终点时,end就减一
  23. end.countDown();
  24. }
  25. }
  26. };
  27. exec.submit(run);
  28. }
  29. System.out.println("Game Start");
  30. // begin减一,开始游戏
  31. begin.countDown();
  32. // 等待end变为0,即所有选手到达终点
  33. end.await();
  34. System.out.println("Game Over");
  35. exec.shutdown();
  36. }
  37. }
  38. Game Start
    No.9 arrived
    No.6 arrived
    No.8 arrived
    No.7 arrived
    No.10 arrived
    No.1 arrived
    No.5 arrived
    No.4 arrived
    No.2 arrived
    No.3 arrived
    Game Over


2.需要等待某个条件到达之后才能做后续下一步的业务,同时当前线程完成后也会触发事件,以便进行后面的操作。



posted @ 2017-08-07 23:13  逍遥叹!!  阅读(281)  评论(0编辑  收藏  举报