Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CountDownLatchDemo #21

Open
whynotybb opened this issue Apr 15, 2019 · 1 comment
Open

CountDownLatchDemo #21

whynotybb opened this issue Apr 15, 2019 · 1 comment

Comments

@whynotybb
Copy link

首先很感谢您的分享,知识点总结的很详细,通俗易懂。经测试,CountDownLatchDemo代码有问题,执行结果与您分享的不一致,但不知是什么问题。

@Buywatermelon
Copy link

Buywatermelon commented Nov 3, 2021

发现这已经是一个2019年的Issue了,想必提问者随着阅历的增加早已找到了答案。而我作为一个正在学习的萌新在2021年看到了这个问题,便尝试着来解答一下。希望对未来的萌新有所帮助

  • 我写了一段至少打印顺序正确的demo
    public void testCountDownLatch() throws InterruptedException {
        CountDownLatch judgeLatch = new CountDownLatch(1);
        CountDownLatch sportLatch = new CountDownLatch(8);
        CountDownLatch sportWaitLatch = new CountDownLatch(8);

        ExecutorService executorService = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {
            executorService.execute(() -> {
                try {
                    log.info(Thread.currentThread().getName() + "运动员等待裁判员响哨!!!");
                    sportWaitLatch.countDown();

                    judgeLatch.await();
                    log.info(Thread.currentThread().getName() + "正在全力冲刺!!!");
                    log.info(Thread.currentThread().getName() + "到达终点");
                    sportLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        sportWaitLatch.await();
        log.info("裁判员发号施令啦!!!");
        judgeLatch.countDown();

        sportLatch.await();
        log.info("所有运动员到达终点,比赛结束");
    }
  • 可以看出区别在于打印“裁判员发号施令啦!!!”语句时,我用一个新的CountDownLatch对象await住了其他线程。
  • 那么很容易就知道原本代码的问题在于:主线程在执行打印“裁判员发号施令啦!!!”时,线程池的遍历执行还没有集中执行到await()处。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants