Created
May 20, 2019 07:58
-
-
Save gonejack/972eea46e017b596e70fdf3ef9aa2a5a to your computer and use it in GitHub Desktop.
Java 关机处理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 推荐做法: | |
static class Stop extends Thread { | |
static void init() { | |
Runtime.getRuntime().addShutdownHook(new Stop()); | |
} | |
@Override | |
public void run() { | |
Thread.currentThread().setName("stop"); | |
App.stop(); | |
Thread.getAllStackTraces().forEach((k, v) -> {logger.debug("剩余线程: {}, {}", k, v);}); | |
} | |
} | |
// 加上信号处理的版本(不建议使用信号处理,Signal是Sun的内部API而且会让程序对系统类型有依赖): | |
static class Stop extends Thread implements SignalHandler { | |
static void init() { | |
Stop appStop = new Stop(); | |
Signal.handle(new Signal("INT"), appStop); | |
Signal.handle(new Signal("TERM"), appStop); | |
} | |
@Override | |
public void handle(Signal signal) { | |
logger.debug("收到信号: {}", signal.toString()); | |
Runtime.getRuntime().addShutdownHook(this); | |
System.exit(0); | |
} | |
@Override | |
public void run() { | |
Thread.currentThread().setName("stop"); | |
App.stop(); | |
Thread.getAllStackTraces().forEach((k, v) -> {logger.debug("剩余线程: {}, {}", k, v);}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment