线程的两阶段终止模式

本文展示了如何使用Java实现两阶段终止设计模式,通过`Thread18`和`TwoPhaseTermination`类来管理和停止工作线程。在`TwoPhaseTermination`中,工作线程会检查中断标志并进行善后处理,确保线程安全停止。
摘要由CSDN通过智能技术生成
package com.company.thread;

/**
 * @description: some desc
 * @author: ruoan
 * @date: 2020/10/24 16:13
 */
public class Thread18 {


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


        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();
        Thread.sleep(5000);
        twoPhaseTermination.stop();


    }
}

/**
 * 两阶段终止设计模式
 */
class TwoPhaseTermination {
    private Thread monitor;

    // 开始线程
    public void start(){
        // 绑定线程任务
        Runnable r = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    work();  // 正常业务
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        interrupted = true;//  如果阻塞的时候被设置打断标记,会被catch到,此时会把标记又重设置为false,这样就不能退出了
                        e.printStackTrace();
                    }
                    if (interrupted) {
                        // 如果监测到外部打断,就自行了断
                        work();// 善后
                        return;
                    }

                }
            }
        };
        monitor = new Thread(r,"monitor thread");
        monitor.start();
    }
    // 线程做的事情
    private void work(){
        System.out.println("I am working...");
    }

    // 关闭线程
    public void stop(){

        if (monitor != null) {
            monitor.interrupt();
        }else{
            throw new RuntimeException("监视线程未初始化");
        }
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值