addShutdownHook钩子函数实例

 

addShutdownHook钩子函数在服务关闭时执行,防止重启服务丢失当前正在执行的任务,但是kill -9 就不行了,通过下面实例你可以很容易上手怎么使用
public class Utility {
    /**
     * Convert current time into int type
     * @param
     * @return timestamp
     */
    public static int getCurrentTimeStamp() {
        return (int) (System.currentTimeMillis());
    }
    private static LinkedBlockingDeque<String> taskRecordQueue = new LinkedBlockingDeque<>();
    private static boolean flag = true;
    private static boolean subflag = true;
    public static void main(String[] args) {

        //往队列添加
        Thread task = new Thread() {
            @Override
            public void run() {
                int t = 1;
                while (flag){
                    try {
                        Thread.sleep(1000);
                        t++;
                        add(t);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        };
        //从队列移除
        Thread task2 = new Thread() {
            @Override
            public void run() {
                while (subflag){
                    try {
                        Thread.sleep(2000);
                        sub();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        };
        task.start();
        task2.start();
        Thread thread = new Thread(){
            @Override
            public void run() {
                clear();
            }
        };
        //添加钩子函数
        Runtime.getRuntime().addShutdownHook(thread);
    }
    //知道此方法执行完,程序才会结束
    public static void clear(){
        flag = false;
        if (taskRecordQueue.peek() != null){
            try {
                System.out.println("clear ***");
                Thread.sleep(1000);
                clear();
            }catch (Exception e){
                e.printStackTrace();
            }
            subflag = false;
        }
    }
    public static void add(int t){
        System.out.println("add "+t);
        taskRecordQueue.addLast("add====="+getCurrentTimeStamp()+"==="+t);
    }
    public static void sub(){
        String a = taskRecordQueue.poll();
        System.out.println("sub******"+a);
    }
}

 

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