Java多线程并发编程——两阶段终止模式(two phase termination)

什么是两阶段终止模式

在一个线程t1中优雅的停止t2线程,优雅指的是给t2一个料理后事的过程,比如释放资源,并不是直接使用stop杀死t2。

两阶段终止模式的原理

根据以上原理图编写测试代码:

package com.leolee.multithreadProgramming.concurrent.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName ThreadStatusTest
 * @Description: TODO
 * @Author LeoLee
 * @Date 2020/11/29
 * @Version V1.0
 **/
@Slf4j
public class ThreadStatusTest {

    
    @Slf4j
    static
    class TwoPhaseTermination {

        private Thread monitor;

        //启动监控线程
        public void start() {
            monitor = new Thread(() -> {
                //模拟线程在运行当中
                for (;;) {
                    Thread monitor = Thread.currentThread();
                    if (monitor.isInterrupted()) {
                        log.info("{}被打断,执行被打断的之后的处理......", monitor.getName());
                        break;
                    } else {
                        try {
                            Thread.sleep(1000);
                            log.info("{}运行正常,执行业务处理......", monitor.getName());
                        } catch (InterruptedException e) {
                            //如果在sleep的时候被打断了,要重置线程的打断状态为true,如果没有这一步,会打断失败,因为sleep wait join会将打断状态设置为false
                            monitor.interrupt();
                            e.printStackTrace();
                        }
                    }
                }
            }, "monitor");

            monitor.start();
        }

        //停止监控线程
        public void stop() {
            monitor.interrupt();
        }

    }


    public static void main(String[] args) throws InterruptedException {

        //两阶段终止模式
        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();
        Thread.sleep(3*1000);
        twoPhaseTermination.stop();
    }
}

执行结果:

12:43:31.500 [monitor] INFO com.leolee.multithreadProgramming.concurrent.thread.ThreadStatusTest$TwoPhaseTermination - monitor运行正常,执行业务处理......
12:43:32.515 [monitor] INFO com.leolee.multithreadProgramming.concurrent.thread.ThreadStatusTest$TwoPhaseTermination - monitor运行正常,执行业务处理......
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.leolee.multithreadProgramming.concurrent.thread.ThreadStatusTest$TwoPhaseTermination.lambda$start$0(ThreadStatusTest.java:243)
	at java.lang.Thread.run(Thread.java:745)
12:43:33.498 [monitor] INFO com.leolee.multithreadProgramming.concurrent.thread.ThreadStatusTest$TwoPhaseTermination - monitor被打断,执行被打断的之后的处理......

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值