两阶段终止设计模式是一种优雅的终止线程的方式。两阶段指的是一个线程发送终止另一个线程的请求,另一个线程接受到请求终止自身并做相应的处理。即两阶段指的是请求阶段和处理阶段。

比如我们要写一个系统监控程序,监控程序有死循环,每2s监控一次系统状况,没有中断的话会一直监控下去,如果有中断,就退出程序,并做一些保存工作。
public class SystemMonitor {
private Thread monitor;
public void start() {
monitor = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
Thread thread=Thread.currentThread();
if (thread.isInterrupted()) {
//
System.out.println("程序被中断,正在保存数据");
break;
}
try {
//可能中断1
Thread.sleep(1000);
//可能中断2
System.out.println("更新监控数据");
} catch (InterruptedException e) {
e.printStackTrace();
//异常中断,interrupt会被重置为false,在调用一遍使之变成true
thread.interrupt();
}
}
}
});
monitor.start();
}
public void stop() {
monitor.interrupt();
}
}
public class TwoPhaseTermination {
public static void main(String[] args) throws InterruptedException {
SystemMonitor monitor=new SystemMonitor();
monitor.start();
Thread.sleep(5000);
monitor.stop();
}
}
两阶段终止设计模式的本质其实就是对中断的封装。这个设计模式的精髓就是catch 异常里面重新调用一遍interrupt方法。因为异常中断interrupt会被重置为false,在调用一遍使之变成true。不然,程序即使调用interrupt方法还是会进入死循环。
两阶段终止设计模式确保线程安全地停止并完成必要的清理工作。在示例中,SystemMonitor类启动一个监控线程,该线程在接收到中断信号后保存数据并退出。中断处理通过在catch块中重新设置interrupt状态来实现,以防止死循环。这种模式是线程间通信的重要实践。
538

被折叠的 条评论
为什么被折叠?



