一.Runtime.addShutdownHook理解
在看别人的代码时,发现其中有这个方法,便顺便梳理一下。
void java.lang.Runtime.addShutdownHook(Thread hook)
该方法用来在jvm中增加一个关闭的钩子。当程序正常退出,系统调用 System.exit方法或虚拟机被关闭时才会执行添加的shutdownHook线程。其中shutdownHook是一个已初始化但并不有启动的线程,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以可通过这些钩子在jvm关闭的时候进行内存清理、资源回收等工作。
二.示例代码
public class TestRuntimeShutdownHook {
public static void main(String[] args) {
Thread shutdownHookOne = new Thread() {
public void run() {
System.out.println("shutdownHook one...");
}
};
Runtime.getRuntime().addShutdownHook(shutdownHookOne);
Runnable threadOne = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread one doing something...");
}
};
Runnable threadTwo = new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread two doing something...");
}
};
threadOne.run();
threadTwo.run();
}
}
输出如下:
thread one doing something...
thread two doing something...
shutdownHook one...
分享到:
相关推荐
Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { server.stop(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); } Or ...
JDK在1.3之后提供了Java Runtime.addShutdownHook(Thread hook)方法,可以注册一个JVM关闭的钩子,这个钩子可以在以下几种场景被调用: 1)程序正常退出 2)使用System.exit() 3)终端使用Ctrl+C触发的...
1 增加线程池consumer优雅退出机制Runtime.getRuntime().addShutdownHook 2 修改部分log输出方式,将原来的 log.info("exceptin:" + e) 修复为 log.info("exception: ", e) 20161227 更新 1 bug fix: 将...
SpringBoot Rest与以下库中的JVM Futures结合 ... Runtime.getRuntime().addShutdownHook(new Thread(SpringBootFuturesSimulation::shutdown)); new SpringApplicationBuilder(SpringWebFuturesAppl
RMI泥浆 跑步 make mud rmiregistry java src.MUDServerMainline <registry> ... 处理用户离开/加入服务器或 MUD,使用MUDServerMainline的shutdownhook MUDServerMainline和服务器端方法playerDisconnect