java – 为什么在显示窗口时不会终止简单的Swing应用程序?

这是一些示例代码:

import javax.swing.*;

public class MyApplicatin {
    public static void main(String args[]) {
        JFrame window = new JFrame();
        window.setSize(100,100);
        window.setVisible(true);

        System.out.println("Should terminate after printing this.");
    }
}

为什么这个小应用程序在打印完最后一行后没有终止?

我的猜测是Swing启动了一个新的非守护进程线程.我正在阅读关于必须一直在单独的线程中使用Java的GUI内容,如果Swing已经使用了一个单独的线程,为什么有人会写这个呢?

最佳答案
为什么要这样?通常,当您显示一个窗口时,您需要控制JVM何时退出. JVM规范中没有任何内容表明当main()方法到达结束时JVM必须退出.

Oracle有some documentation on this specific issue

The reason is that AWT encapsulates asynchronous event dispatch machinery to process events AWT or Swing components can fire. The exact behavior of this machinery is implementation-dependent. In particular, it can start non-daemon helper threads for its internal purposes. In fact, these are the threads that prevent the example above from exiting.

这个机器中的一个(三个)限制是这样的:

There is at least one alive non-daemon thread while there is at least one displayable AWT or Swing component within the application (see 07001).

这意味着只要有可显示的AWT / Swing组件,JVM就不会自行退出.

警告:处置所有可显示的组件并不一定意味着非守护程序线程消失了:

It depends on the implementation if and when the non-daemon helper threads are terminated once all components are made undisplayable.

转载注明原文:java – 为什么在显示窗口时不会终止简单的Swing应用程序? - 代码日志