• 如何中断线程


    已经被抛弃的方法

    1、通过调用stop()方法停止线程(这个方法太暴力而且不安全的,为什么呢?比如说线程A调用线程B的stop方法,去停止线程B。这个时候线程A这个时候并不知道线程B当前是执行情况,这种突然间的停止,会导致线程B的一些清理工作无法完成,而且会导致线程B会马上释放锁,会引发数据不同步的情况)

    2、通过调用suspend()和resume()方法

    目前使用的方法

    1、调用interrupt(),通知线程应该中断了

      1.1 如果线程处于被阻塞状态,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常

      1,.2 如果线程处于正常活动状态,那么会设置该线程的中断标记为true。被设置中断标记的线程依然可以正常运行,不受影响

    2、 需要被调用的线程配合中断

      2.1 在正常运行任务时,经常检查本线程的中断标记位,如果被设置了中断标记就自动停止线程

    public class InterruptDemo {
        public static void main(String[] args) throws InterruptedException {
            Runnable interruptTask = new Runnable() {
                @Override
                public void run() {
                    int i = 0;
                    try {
                        //在正常运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程
                        while (!Thread.currentThread().isInterrupted()) {
                            Thread.sleep(100); // 休眠100ms,子线程会处于阻塞状态
                            i++;
                            System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + ") loop " + i);
                        }
                    } catch (InterruptedException e) {
                        //在调用阻塞方法时正确处理InterruptedException异常。(例如,catch异常后就结束线程。)
                        System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + ") catch InterruptedException.");
                    }
                }
            };
            Thread t1 = new Thread(interruptTask, "t1");
            System.out.println(t1.getName() +" ("+t1.getState()+") is new.");
    
            t1.start();                      // 启动“线程t1”
            System.out.println(t1.getName() +" ("+t1.getState()+") is started.");
    
            // 主线程休眠300ms,然后主线程给t1发“中断”指令。
            Thread.sleep(300);
            t1.interrupt();
            System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
    
            // 主线程休眠300ms,然后查看t1的状态。
            Thread.sleep(300);
            System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
        }
    }


    t1 (NEW) is new.
    t1 (RUNNABLE) is started.
    t1 (RUNNABLE) loop 1
    t1 (RUNNABLE) loop 2
    t1 (TIMED_WAITING) is interrupted.
    t1 (RUNNABLE) catch InterruptedException.
    t1 (TERMINATED) is interrupted now.

      

  • 相关阅读:
    DroidParts 中文系列教程(基于官方教程)
    IDEA添加其他项目为库文件的方法
    IDEA 部署项目的时候出错:Jar not loaded错误
    解决IDEA导入Myclipse项目的时候没有识别为Web项目的问题
    IDEA中安装及配置SVN
    VirtualBox下设置 XP虚拟机桥接模式
    主机上设置共享文件夹供虚拟机访问
    JS的splice()方法在for循环中使用可能会遇到的坑
    Eclipse优化
    State Design Pattern
  • 原文地址:https://www.cnblogs.com/vingLiu/p/10665262.html
Copyright © 2020-2023  润新知