两阶段打断终止
在线程T1中优雅的终止另线程T2,也就是给线程T2在收到打断指令后不是直接强制的停止T2线程而是给T2一些缓冲时间处理后事,处理完之后T2再自动停止。

实现方法无非就是在T2线程中判断自己的线程是否被打断了,被打断了就是执行一些后续操作执行完之后自行退出,加一个if判断即可。
代码:
@Slf4j
public class TestTwoInterrupted {
public static void main(String[] args) throws InterruptedException {
TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
twoPhaseTermination.start();
Thread.sleep(3500);
log.debug("mian线程打断监控线程");
twoPhaseTermination.stop();
}
}
@Slf4j
class TwoPhaseTermination{
private Thread monitor;
public void start(){
monitor = new Thread(() -> {
while (true){
Thread t = Thread.currentThread();
if (t.isInterrupted()){
log.debug("处理后事");
break;
}
try {
Thread.sleep(1000);
log.debug("监控");
} catch (InterruptedException e) {
e.printStackTrace();
t.interrupt();
}
}
});
monitor.start();
}
public void stop(){
if(monitor != null){
monitor.interrupt();
}
}
}
执行结果

总结
总的来说就是有点类似电脑的关机,不是直接拔电源而是先关闭电脑上的一些应用安全关机。留给线程缓冲的时间。

215

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



