??????????Java?????芯????????????????些?????????????????????????????JVM???????????些????????????Java?械?ShutdownHook?????????????
????JDK??1.3???????Java Runtime.addShutdownHook(Thread hook)????????????????JVM??????????????????????????????????????
????1?????????????
????2?????System.exit()
????3????????Ctrl+C???????卸?
????4???????
????5?????Kill pid?????????
????????????kill -9 pid?????JVM?????????????谩?
??????JDK?蟹???????????
????public void addShutdownHook(Thread hook)
????????
????hook -- ????????????未???????????????JVM????????写???
??????
????IllegalArgumentException -- ???????????????????????????卸?????????谢????????
????IllegalStateException -- ???????????????????????
????SecurityException -- ??????????????????????????RuntimePermission??“shutdownHooks”??
?????????????
???????Timer????????????????????????????危????System.exit()??????????????????CleanWorkThread ?校????timer???校???????????????????
package com.netease.test.java.lang;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Date: 14-6-18
* Time: 11:01
* ????ShutdownHook
*/
public class TestShutdownHook {
//????????
static Timer timer = new Timer("job-timer");
//??????????
static AtomicInteger count = new AtomicInteger(0);
/**
* hook???
*/
static class CleanWorkThread extends Thread{
@Override
public void run() {
System.out.println("clean some work.");
timer.cancel();
try {
Thread.sleep(2 * 1000);//sleep 2s
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//??hook???????????????????
Runtime.getRuntime().addShutdownHook(new CleanWorkThread());
System.out.println("main class start ..... ");
//?????
timer.schedule(new TimerTask() {
@Override
public void run() {
count.getAndIncrement();
System.out.println("doing job " + count);
if (count.get() == 10) {  //????10?????
System.exit(0);
}
}
}?? 0?? 2 * 1000);
}
}
???????泻??????????????????????胁???????kill -9 pid???????Hook????????