CountDownLatch的使用
概念:CountDownLatch是java.util.concurrent包中一个类,CountDownLatch只要提供的机制是多个(具体数量等于初始化CountDownLatch时count的值)线程都达到了预期状态或者完成了预期工作时触发事件,其他线程可以等待这个事件来触发自己后续的工作。等待的线程可以是多个,即CountDownLatch可以唤醒多个等待的线程。到达自己预期状态的线程会调用CountDownLatch的countDown方法,而等待的线程会调用CountDownLatch的await方法。
我们平时如果想要去玩lol,首先是不是应该打开电脑,然后登陆lol,然后才可以玩呢,本文以玩游戏为例,简单介绍下CountDownLatch的使用
@Slf4j public class CountDownLatchDemo { static class TurnOnTheComputer implements Runnable { private CountDownLatch latch; public TurnOnTheComputer(CountDownLatch countDownLatch) { this.latch = countDownLatch; } @Override public void run() { log.info("打开电脑..."); latch.countDown(); } } static class LoginLOL implements Runnable { private CountDownLatch latch; public LoginLOL(CountDownLatch countDownLatch) { this.latch = countDownLatch; } @Override public void run() { log.info("登录LOL..."); latch.countDown(); } } public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(2); new Thread(new TurnOnTheComputer(countDownLatch)).start(); new Thread(new LoginLOL(countDownLatch)).start(); countDownLatch.await(); log.info("开始游戏 ..."); } }
结果如下:
CountDownLatch: 一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行。
CyclicBrrier: N个线程相互等待,任何一个线程完成之前,所有的线程都必须等待。