How do I implement graceful termination in Java?

后端 未结 2 842
渐次进展
渐次进展 2021-02-20 02:09

Say for instance I have my application running in a Linux terminal and I press \"CTRL+C\" on my keyboard to kill the process it will terminate the Java program.

Is there

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-20 02:42

    This works for me, capturing SIGINT/Ctrl-C on Linux:

    public class TestShutdownHook
    {
        public static void main(final String[] args) throws InterruptedException
        {
            Runtime.getRuntime().addShutdownHook(new Thread()
            {
                @Override
                public void run()
                {
                    System.out.println("Shutdown hook ran!");
                }
            });
    
            while (true)
            {
                Thread.sleep(1000);
            }
        }
    }
    

提交回复
热议问题