线程中断标志位 interrupt()、interrupted()、isInterrupted() 的认识

常见问题

首先你是怎么去关闭一个开启的线程、调用中断方法之后,线程就立即停止运行吗?

带着这两个问题探讨一下,主要围绕着这三个方法讲述: interrupt()interrupted()isInterrupted(),归类为中断

什么是中断标识位?

首先一个线程不应该有其他线程来强制中断或者停止,而是线程自己停止,所以之前老版本的 stop()、suspend()、resume() 方法都已经 @Deprecated 过期了。

其次 在 Java 中没法立即停止一个线程,然后停止线程又是显得极为重要,那么又该如何取消一个耗时严重的线程呢?这里出现了一种协商机制——中断机制

中断机制是一种协商合作机制,Java 没有给中断任何语法,中断的过程完全需要程序员自己开发,若想中断一个线程,你可以手动调用 Thread.interrupt() 方法,该方法也仅仅是将此线程的中断标识设置成 true;接着你还是要自己写一个不断检查当前线程标识位的操作,比如 while 循环等等,如果检测到为 true,就是表示要退出当前线程。

下面就开始演示怎么去优雅的中断线程?

在此之前先来简单的描述下 interrupt()interrupted()isInterrupted() 这三个方法作用。

方法描述
public void interrupt()实例方法
仅仅就是将线程中断标识位设置成 true,不会停止线程
public static boolean interrupted()静态方法,调用方式:Thread.interrupted()
判断线程是否中被中断,并清除当前中断标志位
这个方法做了两件事:
1、返回当前线程中断标识位
2、然后将当前线程中断标识设置成 false
public boolean isInterrupted()实例方法
判断当前线程是否被中断

案例1

直接看代码如下:

public class ThreadDemo {

    static volatile boolean flag = false;

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (flag) {
                    System.out.println(">>>>>>线程退出" + Thread.currentThread().isInterrupted());
                    break;
                }
                System.out.println(">>>>>>run.....");
            }
        }).start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            flag = true;
        }).start();
    }
}

运行结果:

>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>线程退出false

第一个线程是个死循环线程,3s 过后线程2修改了线程中断标志位 flag = false,线程1检测到该值被修改过了,直接退出当前线程。这也是一种比较常见的线程退出的方式。

案例2

这也是一种超级常见的优雅退出线程方式:

public class ThreadDemo {

    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    System.out.println(">>>>>>线程退出" + Thread.currentThread().isInterrupted());
                    break;
                }
                System.out.println(">>>>>>run.....");
            }
        }).start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            atomicBoolean.set(true);
        }).start();
    }
}

案例1、2 都是通过自己额外定义共享变量来充当中断标志位,也是最常用的一种,下面是通过线程自带的中断标识位来控制线程退出。

案例3


public class ThreadDemo3 {

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(">>>>>>线程退出" + Thread.currentThread().isInterrupted());
                    break;
                }
                System.out.println(">>>>>>run.....");
            }
        });

        thread.start();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            thread.interrupt();
        }).start();
    }
}

运行结果:

>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>线程退出true

调用线程提供的方法 thread.interrupt() 来设置线程中断标识。此时只是修改了中断标识,并不是停止线程,停止线程还是要自己检查标识位然后自己做线程退出。

调用成功之后,通过 Thread.currentThread().isInterrupted() 方法来查看线程标识位是 true,从而停止线程,这是不通过额外添加共享变量就能够优雅的退出线程的常见方式。

案例4


public class ThreadDemo4 {

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(">>>>>>线程退出" + Thread.currentThread().isInterrupted());
                    break;
                }
                try {
                    // 线程中存在阻塞操作
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(">>>>>>run.....");
            }
        });
        thread.start();

        new Thread(()->{
            try {
                TimeUnit.MICROSECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(">>>>>>>线程中断标识为1:"+thread.isInterrupted());
            thread.interrupt();
        }).start();

        System.out.println(">>>>>>>线程中断标识为2:"+thread.isInterrupted());
    }
}

运行结果:

>>>>>>>线程中断标识为1:false
>>>>>>>线程中断标识为2:false
>>>>>>run.....
java.lang.InterruptedException: sleep interrupted
	at java.base/java.lang.Thread.sleep(Native Method)
	at main.future.ThreadDemo4.lambda$main$0(ThreadDemo4.java:16)
	at java.base/java.lang.Thread.run(Thread.java:834)
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....
>>>>>>run.....

如果运行的线程中存在阻塞操作(wait()、join()、sleep()) 就是这三个方法,刚好我们的程序中存在这个 sleep() 阻塞操作,结果去中断线程发现不太愿意,直接给你抛出了异常,并把标识位重置了。所以运行结果一直在打印,线程就不会退出。

这里我们可以看下 interrupt() 方法的源码中有说到,对于线程中存在 wait()、join()、sleep() 方法的,你要是敢调用 interrupt() 方法来中断我,我就给你抛出一个 InterruptedException 异常。

这里需要注意如果是 LockSupport.park() 的话是不会抛出这个异常的,特别注意了。

在这里插入图片描述

所以我们还需要再 catch() 语句块中再次调用 interrupt() 方法,再次修改终端标识位。看案例5。

案例5

public class ThreadDemo4 {

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(">>>>>>线程退出" + Thread.currentThread().isInterrupted());
                    break;
                }
                try {
                    // 线程中存在阻塞操作
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 优雅不失摆烂,重新再次调用 interrupt() 修改标识位
                    Thread.currentThread().interrupt();
                }

                System.out.println(">>>>>>run.....");
            }
        });
        thread.start();

        new Thread(()->{
            try {
                TimeUnit.MICROSECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(">>>>>>>线程中断标识为1:"+thread.isInterrupted());
            thread.interrupt();
        }).start();

        System.out.println(">>>>>>>线程中断标识为2:"+thread.isInterrupted());
    }
}

运行结果:

>>>>>>>线程中断标识为2:false
>>>>>>>线程中断标识为1:false
>>>>>>run.....
>>>>>>线程退出true
java.lang.InterruptedException: sleep interrupted
	at java.base/java.lang.Thread.sleep(Native Method)
	at main.future.ThreadDemo4.lambda$main$0(ThreadDemo4.java:16)
	at java.base/java.lang.Thread.run(Thread.java:834)

可以发现线程已经成功退出了。这也是一种常用手段让线程优雅的退出。

案例6

最后再来演示一下 Thread.interrupted() 静态方法的使用,代码如下:

public class ThreadDemo5 {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"1---"+Thread.interrupted());
        System.out.println(Thread.currentThread().getName()+"2---"+Thread.interrupted());
        System.out.println("1111111");
        Thread.currentThread().interrupt();// false==>true
        System.out.println("2222222");
        System.out.println(Thread.currentThread().getName()+"3---"+Thread.interrupted());
        System.out.println(Thread.currentThread().getName()+"4---"+Thread.interrupted());
    }
}

运行结果:

main1---false
main2---false
1111111
2222222
main3---true
main4---false

第一个 false 表示线程初始状态肯定是 false
第二个 false 因为第一个线程把标识位重置了,所以还是 false
第三个 true 因为调用了 interrupt() 方法将中断标识位设置成了 true
第四个 false 因为第三个调用了 Thread.interrupted() 方法,重置了中断标识位,所以最终还是 false

进入到 interrupted() 静态方法源码,如下:

在这里插入图片描述

明显可以看到传入的是 true,表示需要清楚线程中断标识位。所以每次调用完这个方法,先会把当前线程的中断状态返回,然后悄悄又把线程中断标志位重置回 false。

注意事项

在调用 interrupt() 方法时一定要注意线程中是否存在 wait()、join()、sleep() 这三个方法,如果存在一定要在 catch() 语句块中再次调用 interrupt() 中断方法,方能退出线程。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔道不误砍柴功

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值