Advertisement

JUC学科学习强化第一课

阅读量:

JUC学习之加强篇【一】

双阶段终止机制

文章结构概览

  • JUC进阶学习教程【一

前言

在多线程编程过程中,当需要主动终止某一特定线程时,采用该模式能够确保线程安全地停止运行。通过这种方式,线程可以在完成当前任务的同时,执行必要的收尾操作后再被关闭。
采用此种模式进行线程关闭时,会产生一定的时间延迟,其主要原因在于目标线程需在完成既定操作之后才能正式进入关闭流程。

演示

复制代码
    @Slf4j(topic = "observer")
    class observer{
    private Thread monitor;
    public void start(){
        monitor = new Thread(()->{
            log.info("线程开始工作……");
            while (true){
                // 获取当前线程的干扰标记位
                Thread thread = Thread.currentThread();
                if(thread.isInterrupted()){
                    log.error("线程被打断开始执行善后工作");

全部评论 (0)

还没有任何评论哟~