java中对于线程中断的理解

对于线程中断的理解

许多小白包括我自己对于java中线程中断一开始的理解是,当一个线程收到中断的时候,它自己就立即中断了,其实这是大错特错的,因为线程在收到interrupt方法的时候,只是一种线程通信,另一个线程告诉该线程你被中断了,但是这个线程是自己去决定在你收到中断信号的处理,我可以继续执行我原来的逻辑,也可以执行中断的逻辑。

理论验证

public class ThreadDemo extends Thread {

    // 继承线程一定要重写run方法
    @Override
    public void run() {
        for (int i = 0;  i < 200000; i++) {
            System.out.println("i:" + i);
        }
    }

    public static void main(String[] args) {
        ThreadDemo threadDemo = new ThreadDemo();
        // 在调用对象方法时,一定是调用线程的run方法 否则就是执行了一个普通方法 interrupt将没有作用
        // threadDemo.run(); 是错误的
        threadDemo.start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 执行线程中断方法
        threadDemo.interrupt();
    }
}

在主线程执行了interrupt()方法后,threadDemo 并没有停止执行,而是继续执行直到打印了199999

。。。。。
i:199992
i:199993
i:199994
i:199995
i:199996
i:199997
i:199998
i:199999

那么怎么才能让线程真正中断呢?

public class ThreadDemo extends Thread {

    // 继承线程一定要重写run方法
    @Override
    public void run() {
    	// 在这里添加判断线程中断信号的方法 接收到线程中断 则不在打印 但是它不会清楚线程中断信号
        for (int i = 0; !Thread.currentThread().isInterrupted() && i < 200000; i++) {
            System.out.println("i:" + i);
        }
    }

    public static void main(String[] args) {
        ThreadDemo threadDemo = new ThreadDemo();
        // 在调用对象方法时,一定是调用线程的run方法 否则就是执行了一个普通方法 interrupt将没有作用
        // threadDemo.run(); 是错误的
        threadDemo.start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 执行线程中断方法
        threadDemo.interrupt();
    }
}

当添加了这行代码后,结果就变成了

....
i:1592
i:1593
i:1594
i:1595
i:1596
i:1597
i:1598
i:1599

线程没有运行到199999

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值