Java中CountDownLatch使用初步

package gj.lang.util.concurrent.countdonwlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * Author: areful
 * Date: 2019/4/24
 */
public class CountDownLatchSample {
    private static class Player implements Runnable {
        private int id;
        private CountDownLatch beginCountDownLatch;
        private CountDownLatch endCountDownLatch;

        private Player(int id, CountDownLatch begin, CountDownLatch end) {
            this.id = id;
            this.beginCountDownLatch = begin;
            this.endCountDownLatch = end;
        }

        @Override
        public void run() {
            try {
                beginCountDownLatch.await();
                System.out.println("CyclicBarrierSample " + id + "起跑...");

                Thread.sleep(new Random().nextInt(1000));
                System.out.println("CyclicBarrierSample " + id + " 到达终点");

                endCountDownLatch.countDown();
                System.out.println("CyclicBarrierSample " + id + "继续干其他事情");
            } catch (InterruptedException ignored) {
            }
        }
    }

    public static void main(String[] args) {
        final int PLAYER_NUM = 5;
        CountDownLatch beginCountDownLatch = new CountDownLatch(1);
        CountDownLatch endCountDownLatch = new CountDownLatch(PLAYER_NUM);

        for (int i = 0; i < PLAYER_NUM; i++) {
            new Thread(new Player(i, beginCountDownLatch, endCountDownLatch)).start();
        }

        try {
            System.out.println("统一起跑");
            beginCountDownLatch.countDown();

            endCountDownLatch.await(); //等待所有运动员到达终点
            System.out.println("结果发送到汇报成绩的系统");
        } catch (InterruptedException ignored) {
        }
    }
}

   

输出结果:

posted on 2019-04-24 17:18  areful  阅读(139)  评论(0编辑  收藏  举报

导航