Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java倒计时闩锁未解锁?为什么最后一行不打印?_Java_Spring_Concurrency - Fatal编程技术网

Java倒计时闩锁未解锁?为什么最后一行不打印?

Java倒计时闩锁未解锁?为什么最后一行不打印?,java,spring,concurrency,Java,Spring,Concurrency,countDownLatch在倒计时()之后将不会等待到零。但是程序被锁定了。最后一次打印从未输出 public static void main(String[] args) throws Exception{ CountDownLatch countDownLatch = new CountDownLatch(1); countDownLatch.await(); new Thread(new Runnable() { @Override

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-------");
}
如果wait方法位于线程(而不是主线程)中,则它可以工作。为什么?

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

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-------");
}
欢迎您:)如果您可以通过选择答案将线程标记为已解决,那将非常棒;)