两阶段终止
两阶段终止设计模式(Two-Phase Termination Pattern)是在处理线程终止的一种设计模式。
在多线程编程中,正确地终止一个正在运行的线程是一个比较复杂的问题,因为线程可能在执行重要的任务,简单地中断它可能会导致数据不一致或者资源泄露。
两阶段终止设计模式提供了一种优雅的方式来终止线程,同时确保线程有机会清理资源并安全退出。
public class Test01 {
public static void main(String[] args) {
TwoParseTermination tpt = new TwoParseTermination();
tpt.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
tpt.stop();
}
}
@Slf4j
class TwoParseTermination{
private Thread monitor;
public void start(){
monitor = new Thread(() -> {
while (true) {
if (monitor.isInterrupted()) {
log.info("已中断");
break;
}
try {
Thread.sleep(1000);
log.info("执行监控记录");
} catch (InterruptedException e) {
e.printStackTrace();
monitor.interrupt();
}
}
});
monitor.start();
}
public void stop(){
monitor.interrupt();
}
}