Java中CountDownLatch使用初步

Posted areful

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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) {
        }
    }
}

   

输出结果:

技术图片

以上是关于Java中CountDownLatch使用初步的主要内容,如果未能解决你的问题,请参考以下文章

对CountDownLatch的初步学习

Java并发多线程编程——CountDownLatch

Java并发编程-CountDownLatch

Java并发编程-CountDownLatch

多线程等待所有子线程执行完使用总结——CyclicBarrier使用和源码初步分析

Java并发包中CountDownLatch的工作原理使用示例