交换器:JVM永远不会停止

时间:2012-12-21 09:52:59

标签: java multithreading synchronize

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永远不会退出?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

最后一行:

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

提供"this came from main thread"与其他线程进行交换,但没有其他线程可以提出反要约。