栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

两阶段终止模式--volatile(让一个线程优雅的终止)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

两阶段终止模式--volatile(让一个线程优雅的终止)

两阶段终止模式–volatile

代码:

package demo1;

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

        Thread.sleep(3500);
        System.out.println("停止监控");
        tpt.stop();
    }

}
class TwoPhaseTermination{
    //监控线程
    private Thread monitorThread;
    private volatile boolean stop=false;

    //启动监控线程
    public void start(){
        monitorThread=new Thread(()->{
           while (true){
               Thread current=Thread.currentThread();
               //是否被打断
               if(stop){
                   System.out.println("料理后事");
                   break;
               }
               try {
                   Thread.sleep(1000);
                   System.out.println("执行监控");
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        },"monitor");
        monitorThread.start();
    }
    public void stop(){
        stop=true;
        monitorThread.interrupt();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/307116.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号