并发编程:为何线程的等待方法都会抛出InterruptException

线程中的Interrupt

线程中存在volatile变量Interrupt,用来标记是否中断。
线程中存在对应的isInterrupted()方法,默认是false。调用thread.interrupt()会把isInterrupted()设置成true。

线程的中断和复位

调用thread.interrupt()会把isInterrupted()设置成true。那么其如何复位呢?
1、Thread.interrupted() 返回当前状态复位,回复到初始状态(false)。注意这是一个静态方法。
Demo

public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("before :" + Thread.currentThread().isInterrupted());
                    System.out.println("before :" + Thread.currentThread().isInterrupted());
                    //返回当前状态并复位
                    boolean interrupted = Thread.interrupted();
                    System.out.println(interrupted);
                    System.out.println("after :" + Thread.currentThread().isInterrupted());
                    System.out.println("after :" + Thread.currentThread().isInterrupted());
                }
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        thread.interrupt();
    }

会打印

before : true
before : true
after : false
after : false

2、InterruptedException
Demo

public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    //直接中断休眠中的线程,复位并抛出异常
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();

        System.out.println(thread.isInterrupted());
    }

你可能感兴趣的:(并发编程:为何线程的等待方法都会抛出InterruptException)