线程的基本操作(五)---中断

为什么需要中断

在线程执行过程中,有很多场景需要终止线程的运行。这时就需要一个方法来结束线程并返回结果。

中断的方法

Thread类中提供了3个有关中断的方法:
interrupt():设置中断标志位为true
interrupted();检测中断标志,如果有设置会清除标志位
isInterrupted():检测中断标志位

使用场景

  • 大家都用过迅雷下载电影,假如一个电影下载到一半,可能是网速太慢了,导致你不想下了,你会删除这个任务。就需要中断这个下载线程。
  • 网上的一些刷票软件,可能会开启多线程去帮你抢票,一旦抢到了就会中断其它线程。

代码演示

public class InterruptTest {
    public static void main(String[] args) {
        Thread thread = new Thread (){
            @Override
            public void run() {
                while(true){
                    if (Thread.currentThread().isInterrupted()){
                        System.out.println("中断线程");
                    }else {
                        System.out.println("还在运行中");
                    }
                }
            }
        };
        thread.start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
}

在这里插入图片描述
截取了一部分结果
程序还一直会运行下去,可以看出并不是真正结束了运行,只是设置了中断标示,可以让程序猿自行处理。
比如加一行代码,随便抛一个异常就能结束线程运行了

if (Thread.currentThread().isInterrupted()){
                        System.out.println("中断线程");
                        throw new NumberFormatException();
                    }

在这里插入图片描述

线程在阻塞状态下调用中断方法会抛出interruptException,所以调用阻塞方法的线程必须捕获该异常如(sleep,wait,join)
上面代码修改一下

public class InterruptTest {
    public static void main(String[] args) {
        Thread thread = new Thread (){
            @Override
            public void run() {
                while(true){
                    try {
                        System.out.println("开始休眠线程");
                        Thread.sleep(1000);
                        System.out.println("线程休眠结束");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
}

在这里插入图片描述

为什么不推荐使用stop()

Thread类中还有一个stop()方法,已经被废弃了
在这里插入图片描述
为什么废弃它,是因为在多线程环境下,其中一个线程调用stop方法会释放线程调用对象上的所有锁,如果该对象还在被其他线程调用,会产生数据不一致的问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值