测试代码: (代码从网上抄的)
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
public class TestShutdownHook {
static Timer timer = new Timer("job-timer");
static AtomicInteger count = new AtomicInteger(0);
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 {
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);
}
}, 0, 2 * 1000);
}
}
--- 经过测试:
经过测试
kill pid
kill -15 pid
System.exit(0) 3种
都会执行钩子
Ctrl+C 只会在 不是后台执行的时候才能执行钩子
kill -9 pid 不会执行钩子
网友评论