两阶段终止设计模式

为什么需要两阶段终止设计模式:
在主线程里创建了临界区对象,主线程里创建了一个线程t1去访问临界区,而临界区里面有一个监控线程(在t1访问临界区调用创建监控线程的方法)当我们需要在另外一个线程里(我的代码里是主线程)想要结束监控线程,那么就调用结束方法去结束监控线程。至于如何结束临界区中的监控线程因为stop方法已经废弃,而interupt也不是终止线程,所以这时我们就需要两阶段终止设计模式,来终止监控线程。
监控线程可以用来监控临界区的各种

普通的两阶段终止设计模式

public class Demotest {

    public static void main(String[] args) throws InterruptedException {
        ThreadMonitor threadMonitor=new ThreadMonitor();
        threadMonitor.start();
        Thread.sleep(3000);//让主线程睡一会
        threadMonitor.stop();

    }

}
class ThreadMonitor{
    private Thread mnoitor;

    //启动被监控的线程
    public void start(){
        mnoitor=new Thread(()->{
            while (true){
                Thread nowthread=Thread.currentThread();//获取当前线程
                if (nowthread.isInterrupted()){//有被打断则调用stop方法
                    break;
                }
                try {
                    nowthread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    nowthread.interrupt();//设置打断标志为true
                    System.out.println("设置了打断标记");
                }
            }
        });
        mnoitor.start();
    }

    //想要停止线程
    public void stop(){
        mnoitor.interrupt();
    }
}

用volatile改进后的两阶段终止设计模式

public class Test_TwoModelStop {
    public static void main(String[] args) throws InterruptedException {
        ShareClass shareClass1=new ShareClass();

        new Thread(()->{
            shareClass1.startmonitorthread();
        }).start();

        Thread.sleep(10);
        shareClass1.stopmonitorthread();


    }
}

class ShareClass{
    private volatile boolean stopflag=false;
    private Thread montiorthread;

    public void startmonitorthread(){
        montiorthread=new Thread(()->{
            while (true){
                if (stopflag){
                    System.out.println("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    
                }
            }
        },"montiorthread");
        montiorthread.start();
    }

    public void stopmonitorthread(){
        stopflag=true;
        montiorthread.interrupt();//这里是让监控线程加入还在睡眠那么就可以结束睡眠,节省时间
    }
}

两阶段终止设计模式还可以用犹豫模式进行优化,这个在我的另外一篇博客
犹豫模式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值