钩子(hook),是一种具有
既定生命周期
的框架工具,在生命周期的各个阶段预留给用户执行一些特定操作的口子,其实是一种面向切面
编程。
例如当 JVM 程序即将退出时,会执行我们注入的 钩子线程。
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("The hook thread 1 is running.");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The hook thread 1 is exit.");
}
}));
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("The hook thread 2 is running.");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The hook thread 2 is exit.");
}
}));
}
当该方法运行结束时,会调用这两个 hook 线程。
应用场景:防止应用程序重复启动
public static void main(String[] args) {
File file = new File("./.lock");
if(file.exists()){
throw new RuntimeException("The program already running.");
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("The program received kill signal.");
file.delete();
}
}));
while(true){
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("The program is running.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}