Java线程-Interrupt如何结束线程?

本文探讨了如何在Java中正确使用中断机制,避免`sleep`, `wait`, `join`导致的中断异常。重点讲解了错误处理方式及Thread.interrupted()方法的应用,以确保线程中断流程的顺畅执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现此中断很简单,启动线程A,然后触发Interrupt

 

但是需要注意,sleep、wait、join等方法,会抛出Interrupt异常,并且设置中断标志位为false,导致判断isinterrupt退出循环失败,这一点需要注意

 

错误写法

public class TestThread extends Thread {

    @Override
    public void run() {
        while(!isInterrupted()){//中断标志位设为false,这里循环无法结束
            Log.d("ZTL","no interrupt!");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                Log.d("ZTL","Interrupt exception!!!");//被拦截
                e.printStackTrace();
            }
        }
        Log.d("ZTL","Thread is interruptend!  state= " + isInterrupted());
    }
}

正确写法

public class TestThread extends Thread {

    @Override
    public void run() {
        while(!isInterrupted()){
            Log.d("ZTL","no interrupt!");
           
        }
        Log.d("ZTL","Thread is interruptend!  state= " + isInterrupted());
    }
}

看一下sleep方法上的备注

* @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.


也就是将中断标志位会被重置为false,并且抛出异常


中断且清空中断标志位的方法为:Thread.interrupted()

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值