ShutdownHook的使用

源碼

import java.util.concurrent.TimeUnit;


public class HookTest {

    public static void main(String[] args) throws InterruptedException{
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hahaha");
            }
        }));

        TimeUnit.SECONDS.sleep(10);

        System.out.println("ending......");
    }
}

打印結果

ending......
Hahahajava

分析

JDK提供了Java.Runtime.addShutdownHook(Thread hook)方法,能夠註冊一個JVM關閉的鉤子,這個鉤子能夠在一下幾種場景中被調用:ide

    程序正常退出spa

    使用System.exit()code

    終端使用Ctrl+C觸發的中斷進程

    系統關閉get

    OutOfMemory宕機源碼

    使用Kill pid命令幹掉進程(注:在使用kill -9 pid時,是不會被調用的)it

相關文章
相關標籤/搜索