java安全退出程序------关闭钩子

时间:2018-05-15 18:25:21   收藏:0   阅读:237
测试代码:

public class TestHook {

public static boolean hookFlag = false;

public static void main(String[] args) {

    Thread shutDownThread = new Thread() {
        public void run() {
            TestHook.hookFlag = true;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("hook success!"+TestHook.hookFlag);
        }
    };
    Runtime.getRuntime().addShutdownHook(shutDownThread);
    System.out.println("hook init" + TestHook.hookFlag);
    while(!TestHook.hookFlag) {
        try {
            Thread.sleep(1000);
            System.out.println("没安全退出");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    System.out.println("安全退出");
}

}


执行命令 kill [pid]


运行结果:

技术分享图片

原文:http://blog.51cto.com/jtech/2116635

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!