0
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永远不会在这里退出?

4

2 回答 2

2

您的线程中有 1 个交换点,但您的主线程中有 2 个交换点。所以第二次交换:String s = exchanger.exchange("this came 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");
    }
}
于 2012-12-21T09:58:33.340 回答
0

最后一行:

String s = exchanger.exchange("this came from main thread");

提议"this came from main thread"与其他线程交换,但没有其他线程可以还价。

于 2012-12-21T10:01:20.370 回答