使用两阶段终止模型优雅的中断线程

3 篇文章 0 订阅
public class StopGenteelly {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        Thread.sleep(100);
        tpt.stop();
    }
}

class TwoPhaseTermination{
    private Thread thread;

    public void start(){
        thread = new Thread(()->{
            while (true){
                if (thread.isInterrupted()){
                    System.out.println("线程被中断,结束线程");
                    break;
                }

                try {
                    System.out.println("做一些工作。。。");
                    Thread.sleep(1000); //在这里中断,会抛出InterruptedException
                } catch (InterruptedException e) {//中断标记会被重置
                    e.printStackTrace();
                    thread.interrupt();
                }
            }
        });

        thread.start();
    }

    public void stop(){
        thread.interrupt();
        System.out.println("中断线程");
    }
}

如果我们需要中断的线程的run()方法中有sleep,wait,join操作,那么在执行这些操作之后,线程进入阻塞状态,中断阻塞状态的线程会抛出InterruptedException异常,并且在抛出异常时会将中断标志重置为false,所以在捕获到这个异常时,重新将中断标志置为true是十分必要的,否则线程将不会被中断。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值