Java并发编程:两阶段终止模式

Two Phase Termination
在一个线程 T1 中如何“优雅”终止线程 T2?这里的【优雅】指的是给 T2 一个料理后事的机会。
在这里插入图片描述

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.TestTwoPhaseTermination")
public class TestTwoPhaseTermination {

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();

        Thread.sleep(3500);
        tpt.stop();
    }

}

/**
 * 两阶段终止
 */
@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination {

    private Thread thread;

    public void start() {
        thread = new Thread(() -> {
            while (true) {
                // 获取当前线程打断标记
                Thread current = Thread.currentThread();
                if (current.isInterrupted()) {
                    // 正常运行打断,不会清除打断标记
                    log.debug("料理后事");
                    break;
                }

                try {
                    // 打断阻塞线程,清除打断标记
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 重新设置打断标记
                    current.interrupt();
                }

            }
        }, "t");

        thread.start();
    }

    public void stop() {
        thread.interrupt();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值