給應用程序注入鉤子程序

package com.thread.hook;

/**
 * 給應用程序注入鉤子程序
 */
public class ExitCapture {

    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("程序將要退出");
            notifyAndRelease();
        }));

        int i = 0;
        while (true){
            try {
                Thread.sleep(1_000);
                System.out.println("working.....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i++;
            if (i==15){

                throw new RuntimeException("error");
            }
        }
    }

    public static void notifyAndRelease(){
        System.out.println("notify to the admin");
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("線程將要釋放資源");
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("已經釋放資源");
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章