当我关闭所有应用程序窗口时,为什么JVM不会终止?

时间:2014-06-05 04:17:52

标签: java swing

我在许多论坛中看到的答案是 - AWT事件调度程序线程不是守护程序线程。您必须显式调用System.exit来终止JVM。

如何成为守护程序线程可能导致JVM关闭该应用程序。因为,它表示只有在所有非守护程序线程死亡后,程序才会退出。

当我们创建一个简单的JFrame并且不发出setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)时,当我们运行程序并且当JVM退出时,程序仍在运行

3 个答案:

答案 0 :(得分:0)

JFrame的默认值是(相当于)HIDE_ON_CLOSE,所以它只是隐藏了框架(你仍然可以将其恢复),因此应用程序仍在运行,因此JVM不会退出。

(但是为什么它是默认值,我没有答案。)

答案 1 :(得分:0)

正如Thread JavaDocs州......

  

所有非守护程序线程的线程都已通过返回而死亡   从调用run方法或抛出异常   传播超出了run方法。

您可以通过调用System.exit

强制JVM终止

我认为您混淆应用程序关闭和JVM终止。您的应用程序在JVM中运行,因此JVM无法终止并使您的应用程序保持运行

答案 2 :(得分:0)

您可能应首先参考API规范。这是它的设计方式。 它清楚地说:

  

  与Frame不同,JFrame有一些关于当用户试图关闭窗口时如何响应的概念。默认行为是在用户关闭窗口时隐藏JFrame。要更改默认行为,请调用setDefaultCloseOperation(int)方法。要使JFrame的行为与Frame实例相同,请使用setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)。

     

http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html

所以它只是调用setVisible(false);默认关闭操作

您可以在JFrame类中检查protected void processWindowEvent(WindowEvent e)的源代码。

/**
 * Processes window events occurring on this component.
 * Hides the window or disposes of it, as specified by the setting
 * of the <code>defaultCloseOperation</code> property.
 *
 * @param  e  the window event
 * @see    #setDefaultCloseOperation
 * @see    java.awt.Window#processWindowEvent
 */
protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);

    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
        switch(defaultCloseOperation) {
          case HIDE_ON_CLOSE:
             setVisible(false);
             break;
          case DISPOSE_ON_CLOSE:
             dispose();
             break;
          case DO_NOTHING_ON_CLOSE:
             default:
             break;
          case EXIT_ON_CLOSE:
              // This needs to match the checkExit call in
              // setDefaultCloseOperation
            System.exit(0);
            break;
        }
    }
}

另外,MadProgrammer的评论在这里是有道理的。