java.lang.Runtim类提供了addShutdownHook(Thread hook)方法,用来添加虚拟机关闭的钩子。
用途
1应用程序正常退出,在退出时执行特定的业务逻辑
2虚拟机非正常退出,比如用户按下ctrl c,操作系统关闭等。在退出时执行必要的挽救措施。
实例:
public class TestOnExit {
public TestOnExit(){
doShutDownWork();
}
private void doShutDownWork(){
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
System.out.println("application will exit ....");
}
});
}
public static void main(String[] args) {
TestOnExit exit=new TestOnExit();
long beginTime=System.currentTimeMillis();
for(int i=0;i<10;i ){
try {
System.out.println("application run the " i "ci");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long endTime=System.currentTimeMillis();
System.out.println("it speat time ..is " (endTime-beginTime));
}
}
郑州建站推广 网站策划 网站建设 网站推广 网站开发 SEO优化 SEO 网站SEO 清软国际 东方清软 国信清软
用途
1应用程序正常退出,在退出时执行特定的业务逻辑
2虚拟机非正常退出,比如用户按下ctrl c,操作系统关闭等。在退出时执行必要的挽救措施。
实例:
public class TestOnExit {
public TestOnExit(){
doShutDownWork();
}
private void doShutDownWork(){
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
System.out.println("application will exit ....");
}
});
}
public static void main(String[] args) {
TestOnExit exit=new TestOnExit();
long beginTime=System.currentTimeMillis();
for(int i=0;i<10;i ){
try {
System.out.println("application run the " i "ci");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long endTime=System.currentTimeMillis();
System.out.println("it speat time ..is " (endTime-beginTime));
}
}
郑州建站推广 网站策划 网站建设 网站推广 网站开发 SEO优化 SEO 网站SEO 清软国际 东方清软 国信清软