Why won't this shutdownhook work?

北城以北 提交于 2020-01-03 15:56:03

问题


This is my main method and it contains a shutdownhook:

public static void main(String args[]) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            JOptionPane.showMessageDialog(null, "Shutdown hook");
        }
        });

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(
            new Runnable() {
                @Override
                public void run() {
                    Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
                    MyFrame frame = new MyFrame();
                    frame.setVisible(true);
                }
            });
}

The problem is the JOptionPane doesn't show up at all. Instead, the frame closes but the app itself still runs. PS. I can't use the WindowClosing event because it doesn't fire on the Cmd+Q command on Mac OS X.


回答1:


The dispatch thread is already shut down, or is likely to be shut down before your submission to the queue is executed.

You need to find another way of trapping the quit events, shutdown hook is there so you can tidy up when the VM is exiting, so you really don't want to by tying up more resources in the UI when it is called.



来源:https://stackoverflow.com/questions/15546775/why-wont-this-shutdownhook-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!