Java CountDownLatch无法解锁?为什么最后一行不打印?

在countDown()之后,countDownLatch将不会等待到零.但该程序已被锁定.最后一次打印永不输出.

public static void main(String[] args) throws Exception{
    CountDownLatch countDownLatch = new CountDownLatch(1);
    countDownLatch.await();

    new Thread(new Runnable() {
        @Override
        public void run() {
            countDownLatch.countDown();
            countDownLatch.countDown();
        }
    }).start();

    System.out.println("------should print-------");
}

如果await方法在一个线程(不是主线程)中,它就可以工作.为什么?

public static void main(String[] args) throws Exception {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();


    new Thread(new Runnable() {
        @Override
        public void run() {
            countDownLatch.countDown();
            countDownLatch.countDown();
        }
    }).start();

    System.out.println("------should print-------");
}
最佳答案
在启动子线程之前,您正在调用await(并停止线程):

public static void main(String[] args) throws Exception{
    CountDownLatch countDownLatch = new CountDownLatch(1);

    new Thread(new Runnable() {
        @Override
        public void run() {
            countDownLatch.countDown();
            countDownLatch.countDown();
        }
    }).start();
    countDownLatch.await();
    System.out.println("------should print-------");
}

转载注明原文:Java CountDownLatch无法解锁?为什么最后一行不打印? - 代码日志