gpt4 book ai didi

java - 交换器 : JVM never stops

转载 作者:行者123 更新时间:2023-12-02 07:22:47 25 4
gpt4 key购买 nike

public static void main(String[] args) throws Exception {
final Exchanger<String> exchanger = new Exchanger<String>();
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + exchanger.exchange("this came from subthread"));
} catch (InterruptedException ex) {
System.out.println("interrupted while waiting for message");
}
}
}).start();

System.out.println(Thread.currentThread().getName() + exchanger.exchange("this came from main thread"));
String s = exchanger.exchange("this came from main thread");
}

输出

mainthis came from subthread
Thread-0this came from main thread

为什么 JVM 这里永远不会退出?

最佳答案

您的线程中有 1 个交换点,但主线程中有 2 个交换点。因此,第二次交换:String s = Exchanger.exchange("this come from main thread"); 永远等待并阻止 JVM 退出。如果您在该行之后添加打印语句,您将看到它不会被执行。

如果您在线程中添加第二个交换器,程序将退出:

public void run() {
try {
System.out.println(Thread.currentThread().getName() + exchanger.exchange("this came from subthread"));
exchanger.exchange("allow JVM to exit here");
} catch (InterruptedException ex) {
System.out.println("interrupted while waiting for message");
}
}

关于java - 交换器 : JVM never stops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13987840/

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