gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:38:30 25 4
gpt4 key购买 nike

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

最佳答案

在启动子线程之前调用 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 不解锁?为什么最后一行不打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50023497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com