调用方
Runtime.getRuntime().addShutdownHook(new ShutdownThread(importUserTag4RedisServer)); public class ShutdownThread extends Thread { private static final Logger log = Logger.getLogger(ShutdownThread.class); private Server server = null; public ShutdownThread(Server server) { this.server = server; } public void run() { log.info("开始停止"); try { log.info("开始停止"+server.getServerName()); server.stopServer(); } catch (Exception e) { log.error("停止"+server.getServerName()+"出现异常", e); } try { while (!server.isStopped()) { log.info(server.getServerName()+"正在停止"); BaseThread.sleep(1000); } } catch (Exception e) { log.error("停止"+server.getServerName()+"出现异常", e); } log.info(server.getServerName()+"已停止"); } } 测试类: public class RunTimeTest { /** * @param args */ public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { System.out.println("thread1..."); } }; Thread thread2 = new Thread() { public void run() { System.out.println("thread2..."); } }; Thread shutdownThread = new Thread() { public void run() { System.out.println("shutdownThread..."); } }; Runtime.getRuntime().addShutdownHook(shutdownThread); thread1.start(); thread2.start(); } } 打印结果: thread2... thread1... shutdownThread... 或者: thread2... thread1... shutdownThread... 结论: 无论是先打印thread1还是thread2,shutdownThread 线程都是最后执行的(因为这个线程是在jvm执行关闭前才会执行)。