您的位置:首页 > 游戏 > 手游 > 两阶段终止

两阶段终止

2024/10/5 20:23:24 来源:https://blog.csdn.net/weixin_74144099/article/details/141173301  浏览:    关键词:两阶段终止

两阶段终止

两阶段终止设计模式(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();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com