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

时间:2018-04-25 13:20:47

标签: java spring concurrency

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

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-------");
}

1 个答案:

答案 0 :(得分:6)

在启动子线程之前,您正在调用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-------");
}