对JVM添加ShutdownHook管理停止时的操作
当JVM
准备停止时,添加ShutdownHook
监听状态,可处理一些对象的生命周期
简单例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public class Demo {
public static void main(String[] args) throws IOException { System.out.println("Start.");
Runtime.getRuntime().addShutdownHook(new Thread(new Hook(),"hook")); Runtime.getRuntime().addShutdownHook(new Thread(new Hook2(),"hook2"));
System.in.read();
System.out.println("Shutdown."); }
static class Hook implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+": Hook Running."); } }
static class Hook2 implements Runnable{ @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+": Hook Running."); } } }
|