线程基础3 线程中断

已经过时的方法:

  1. 暂停 suspend()
  2. 恢复 resume()
  3. 停止 stop()

过时原因:

suspend()方法在调用后,线程不会释放已经占有的资源(比如锁),而是占有着资源进入睡眠状态,这样容易引发死锁问题。stop()方法在终结一个线程时不会保证线程的资源正常释放。

线程中断的三个方法:

  • interrupt()             :中断线程
  • interrupted()         :清除中断标示
  • isInterrupted()      :返回线程中断状态

注意:

  1. 线程在阻塞的时候才会响应中断 (比如当前线程Thread.sleep(100)的时候)
  2. 线程的interrupt() 方法会抛出一个InterruptedException 并且会清除当前线程的的中断标示
  3. 线程的调用 interrupt()中断后 再调用清除方法 interrupted() 第一次会返回true 第二次会false
public class ThreadStop extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("1初始中断状态:" + this.isInterrupted());
            this.interrupt(); // 调用中断
            System.out.println("2调用后中断状态" + this.isInterrupted());
            System.out.println("3清除中断标记" + interrupted());
            System.out.println("4清除中断标记后中断状态" + this.isInterrupted());
            this.interrupt(); // 因为清除了中断标记线程不会再中断  所以再次调用中断
            System.out.println("5调用interrupt后中断状态" + this.isInterrupted());
            Thread.sleep(100);// 阻塞响应中断
            System.out.println("6当前文字不打印因为线程已经中断");
        } catch (InterruptedException e) {
            System.out.println("7线程被终止了InterruptedException 会清除中断标记 状态为" + this.isInterrupted());
        }
    }
    public static void main(String[] args) {
        ThreadStop ts = new ThreadStop();
        ts.start();
    }
}

执行结果:

1初始中断状态:false
2调用后中断状态true
3清除中断标记true
4清除中断标记后中断状态false
5调用interrupt后中断状态true
7线程被终止了InterruptedException 会清除中断标记 状态为false

线程的中断可以让程序员自定义的处理中断从而可以更加灵活的处理当前线程中断时需要处理的资源和业务逻辑 

除了jdk自带的线程中断我们也可以定义一个volatile 变量来标示当前线程是否要中断比如

public class ThreadStop extends Thread {

    public static volatile boolean isInterrupte = false;

    @Override
    public void run() {
        if(!isInterrupte){ 
            System.out.println("--");
        }
    }

    public static void main(String[] args) {
        ThreadStop ts = new ThreadStop();
        ts.start();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_25825923/article/details/82763852