2虚拟机非正常退出,比如用户迟镇按下郑旦升ctrl+c、OutofMemory宕机、 *** 作系统关闭等。在喊老退出时执行必要的挽救措施。
public class JVMHook {
public static void start(){
System.out.println("The JVM is started")
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
try{
//do something
System.out.println("The JVM Hook is execute")
}catch (Exception e) {
e.printStackTrace()
}
}
})
}
public static void main(String[] args) {
start()
System.out.println("The Application is doing something")
try {
Thread.sleep(3000)
} catch (InterruptedException e) {
e.printStackTrace()
}
}
}
输出结果:
The JVM is started
The Application is doing something
The JVM Hook is execute
1.public class TestShutDownHook {
2.
public TestShutDownHook() {
3.
doShutDownWork()
4.
}
5.
private void doShutDownWork() {
6.
Runtime run=Runtime.getRuntime()//当前段族燃 Java 应用程序相关的运行时对象。
7.
run.addShutdownHook(new Thread(){ //注册新的虚拟机来关闭钩子
8.
@Override
9.
public void run() {
10.
//程序结束时进行的穗弯 *** 作
11.
System.out.println("程序结束调用")
12.
}
13.
})
14.
}
15.
public static void main(String[] args) {
16.
new TestShutDownHook()
17.
for (int i = 0i <1000i++) { // 在这里增添握虚您需要处理代码 }
18.
System.out.println(i)
19.
}
20.
}
21.
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)