java 监控主程序 结束 退出 报警 提示 加钩子 ShutdownHook

java 监控主程序 结束 退出 报警 提示 加钩子 ShutdownHook,第1张

有时候会有需求:想要监控主程序结束。在主程序结束的时候,执行一些代码。

可以用Runtime中的addShutdownHook

package com.thread;

public class T1_Hook {

    public static void main(String[] args) {
        System.out.println("start");
        //加钩子:主线程结束走该线程
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                super.run();
                System.out.println("============主程序结束================");
            }
        });
        System.out.println("end");

        //其他的线程:模拟springboot中,主线程跑起来后,其中的各种线程
        new Thread(()->{
            int i = 0;
            while (i < 10) {
                System.out.println(i++);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

感谢此文 

为主程序增加Hook,监控主线程的退出_日志的博客-CSDN博客

看下Runtime的源码:

public class Runtime {
    //单例模式
    private static Runtime currentRuntime = new Runtime();
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    //不让别人实例化
    private Runtime() {}
...
}

Runtime使用了单例模式

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/919706.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存