How does CTRL-C work with Java program

人盡茶涼 提交于 2019-12-10 12:36:24

问题


When I press ctrl-c in console in what sequence are application threads stopped and shutdown hooks called?


回答1:


According to the javadocs, the registered shutdown hooks are called in an unspecified order when the JVM starts shutting down; e.g. in response to a CTRL-C.

Application threads are not "stopped" in any well defined way. Indeed, they could continue running up right until the process exits.

If you want your threads to be shut down in an orderly fashion, you need to do something in a shutdown hook to cause this to happen. For example, a shutdown hook could call Thread.interrupt() to tell worker threads to stop what they are doing ... and call join() to make sure that it has happened.




回答2:


I know that you can specify what should happen when Ctrl-C is being hit by adding a shutdown hook. But I'm not sure in what order.

private static void createShutDownHook()
{
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
    {

        @Override
        public void run()
        {
            System.out.println();
            System.out.println("Thanks for using the application");
            System.out.println("Exiting...");

        }
    }));
}


来源:https://stackoverflow.com/questions/11435533/how-does-ctrl-c-work-with-java-program

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