两阶段终止模式 Two Phase Termination
在一个线程T1中如何“优雅”终止线程T23这里的【优雅】指的是给T2一个料理后事的机会.
错误思路
1.使用线程对象的stop()方法停止线程
stop方法会真正杀死线程,如果这时线程锁住了共享资源,那么当它被杀死后就 再也没有机会释放锁,其它线程将永远无法获取锁
2.使用 System.exit(int)方法停止线程
目的仅是停止一个线程,但这种做法会让整个程序都停止
两阶段终止模式流程

实现代码
package com.yuanzi.Interrupt;import lombok.extern.slf4j.Slf4j;/*** @program: practice* @description: 两阶段终止模式* @author: yuanzi* @create: 2021-06-09 02:13**/@Slf4j(topic = "c.TwoPhaseTemination")public class TwoPhaseTemination {private Thread monitor;//启动监控线程public void start() {monitor = new Thread(() -> {while (true) {Thread currentThread = Thread.currentThread();if (currentThread.isInterrupted()) {log.debug("料理后事");break;}try {Thread.sleep(1000); //情况1log.debug("执行监控记录"); //情况2} catch (InterruptedException e) {e.printStackTrace();//重新设置打断标记currentThread.interrupt();}}});monitor.start();}//停止监控线程public void stop() {monitor.interrupt();}public static void main(String[] args) throws InterruptedException {TwoPhaseTemination tpt = new TwoPhaseTemination();tpt.start();Thread.sleep(5000);tpt.stop();}}
运行结果
