用两阶段终止模式来终止线程

使用stop()方法会将线程完全终止,没有机会释放锁,这样会使锁永远无法释放。
使用System.exit(int)方法会杀死整个进程。
interrupted():测试当前线程是否中断 。 当前线程指运行this.interrupted()的进程,并且此方法具有清除状态的作用。
isInterrupted():测试线程是否已经中断,不是静态方法,需要创建出线程对象,测试该对象的中断状态,并且不会清除状态。

 //两阶段终止模式
    static Thread test3(){
        Thread thread = new Thread(()->{
            while (true) {
                Thread thread1 = Thread.currentThread();
                if (thread1.isInterrupted()){
                    System.out.println("料理后事。。。");
                    break;
                }
                    System.out.println("运行。。。");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        thread1.interrupt();
                    }

            }
        });
        return thread;
    }

public static void main(String[] args) throws InterruptedException {
        Thread thread = test3();
        thread.start();
        Thread.sleep(3500);
        thread.interrupt();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值