??????????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????????