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);
    }
}

 

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