两阶段终止

两阶段终止

两阶段终止设计模式(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();
    }
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林小果呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值