8.设计模式-两阶段终止(优雅停机)
优雅停机
应用程序停止之前,内部的线程如果有业务正在执行,如何优雅的关闭。
- 要终止一个线程,不要直接stop(),因为这个线程可能还有事情没有完成,比如还有锁没有释放
- 也不要System.exit(), 因为这样直接结束进程了
- stop方法已经过时了
使用interrupt方法实现
@Slf4j(topic = "c.c.e.d.Monitor")
public class Monitor {Thread thread;public void start() {thread = new Thread(() -> {while (true) {Thread currentThread = Thread.currentThread();// 执行业务逻辑之前先检查下打断标记,若被打断了,则停止线程,清理资源if (currentThread.isInterrupted()) {// 在这里可以做一些清理资源的工作log.debug("线程被打断了,停止");break;}try {log.debug("执行业务逻辑。。");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();// 若线程在sleep的时候被打断,则会抛出异常,此时打断标记还是false// 可以手动设置为true,这样下次循环的时候,就会停止currentThread.interrupt();}}});thread.start();}public void stop() {thread.interrupt();}
}