• 如何正确的中断线程?你的姿势是否正确


    Java停止线程的逻辑(协同、通知)

    在Java程序中,我们想要停止一个线程可以通过interrupt方法进行停止。但是当我们调用interrupt方法之后,它可能并不会立刻就会停止线程,而是通知线程需要停止。线程接收到通知之后会根据自身的情况判断是否需要停止,它可能会立即停止,也有可能会执行一段时间后停止,也可能根本就不停止。

    那么Java为什么要选择这种非强制性的线程中断呢?其实更多是为了数据安全,保证程序的健壮性。因为我们不知道程序正在做什么事情。如果贸然停止,可能会造成数据的错乱、不完整。

    一个简单的例子

    1. public class _24_ThreadTest implements Runnable {
    2. @Override
    3. public void run() {
    4. int count = 0;
    5. while (!Thread.currentThread().isInterrupted() && count <= 2000) {
    6. System.out.println("count: " + count++);
    7. }
    8. }
    9. public static void main(String[] args) throws Exception {
    10. _24_ThreadTest threadTest = new _24_ThreadTest();
    11. Thread thread = new Thread(threadTest);
    12. thread.start();
    13. Thread.sleep(10);
    14. // 中断线程
    15. thread.interrupt();
    16. }
    17. }
    18. 复制代码

    这个例子是一个简单的通过interrupt中断线程的案例,run方法中通过判断当前线程是否中断,并且count是否大于2000来进行循环。如果线程中断则退出循环,线程执行结束。这种就属于线程正常停止的情况。

    Sleep是否会收到线程中断信号

    1. public class _24_ThreadTest implements Runnable {
    2. @Override
    3. public void run() {
    4. int count = 0;
    5. while (!Thread.currentThread().isInterrupted() && count <= 2000) {
    6. try {
    7. System.out.println("count: " + count++);
    8. // 子线程睡眠
    9. Thread.sleep(1000 * 2);
    10. System.out.println("方法体:" + Thread.currentThread().isInterrupted());
    11. } catch (InterruptedException e) {
    12. System.out.println("异常:" + Thread.currentThread().isInterrupted());
    13. // 线程中断标志位被重置为false
    14. e.printStackTrace();
    15. }
    16. }
    17. }
    18. public static void main(String[] args) throws Exception {
    19. _24_ThreadTest threadTest = new _24_ThreadTest();
    20. Thread thread = new Thread(threadTest);
    21. thread.start();
    22. Thread.sleep(10);
    23. // 中断线程
    24. thread.interrupt();
    25. }
    26. }
    27. 复制代码

    如果在子线程中睡眠中,主线程通过interrupt方法进行中断,那么子线程还能不能收到中断信号。其实在这种情况下线程也是可以接收到信号通知的,这个时候会抛出InterruptedException,并且将线程中断标志位设置为false。

    在抛出异常后,线程标志位被设置为false,那么在下次循环判断count没有为false的情况下,还是可以进入循环体的。这个时候线程就无法停止。

    执行结果:

    案例场景

    在进行一些后台任务通过线程跑的时候,如果在循环中遇到线程中断异常,我们需要终止当前任务,并且告诉客户端当前任务执行失败的是哪条记录,这种情况下就可以通过异常中再次中断的方式来停止线程,并且可以返回给客户端当前出现异常的记录是哪条。而不会是接着执行下去。

    解决方法

    1. public class _24_ThreadTest implements Runnable {
    2. @Override
    3. public void run() {
    4. int count = 0;
    5. while (!Thread.currentThread().isInterrupted() && count <= 2000) {
    6. try {
    7. System.out.println("count: " + count++);
    8. // 子线程睡眠
    9. Thread.sleep(1000 * 2);
    10. Thread.currentThread().interrupt();
    11. System.out.println("方法体:" + Thread.currentThread().isInterrupted());
    12. } catch (InterruptedException e) {
    13. // 再次中断
    14. Thread.currentThread().interrupt();
    15. System.out.println("异常:" + Thread.currentThread().isInterrupted());
    16. e.printStackTrace();
    17. }
    18. }
    19. }
    20. public static void main(String[] args) throws Exception {
    21. _24_ThreadTest threadTest = new _24_ThreadTest();
    22. Thread thread = new Thread(threadTest);
    23. thread.start();
    24. Thread.sleep(10);
    25. // 中断线程
    26. thread.interrupt();
    27. }
    28. }
    29. 复制代码

    既然我们已经知道,在出现线程中断异常之后线程中断标志位会被重置为false,那么我们可以在异常中手动的再次中断当前线程,那么就可以完全停止线程任务。

    总结

    上面我们简单介绍了如何正确的停止线程,如果在以后的面试中被问到这类问题,那么你是不是可以流畅的回答面试官了。

    在run方法中遇到异常,我们是不能直接生吞的,一定要做处理,你可以是简单的日志记录,也可以中断线程。但就是不能不做任何处理。

    其实还有其他的一些方法来停止线程,比如stop(),这类方法已被舍弃,这种强制停止可能会引起线程的数据安全问题,所以已经不再推荐使用了。

     

  • 相关阅读:
    贝锐花生壳+Fooocus,快速自建可远程访问的SDXL,平替Midjourney
    驱动开发:内核字符串拷贝与比较
    [计算机毕业设计定制]精品微信小程序学生公寓生活管理系统|前后分离VUE[包运行成功]
    核函数简介
    《对比Excel,轻松学习Python数据分析》读书笔记------数据可视化
    RabbitMQ: 死信队列
    『C语言进阶』字符函数和内存函数(2)
    VS2022ide下使用C++实现简谐振动,C语言程序设计简谐运动的模拟,C语言课程设计简谐振动实验的模拟。
    swift类型属性及其注意点
    Day31|贪心算法1
  • 原文地址:https://blog.csdn.net/m0_71777195/article/details/126345647