Thread中Thread.interrupted()和this.isInterrupted()方法的区别

区别一:

Thread.interrupted()是静态方法,作用于当前线程

isInterrupted()是成员方法,作用于Thread类的实例

区别二:

Thread.interrupted()方法在返回中断状态位的同时,清除了状态位状态

isInterrupted()方法只查询当前的状态位,并不对状态位做任何操作

如:

public static void main(String[] args){

        // 查询中断状态
        System.out.println("Main t is interrupted ? " + Thread.currentThread().isInterrupted());

        // 清除状态位
        System.out.println("Main t is interrupted ? " + Thread.interrupted());

        // 设置线程中断状态为true,执行阻塞方法(sleep,join等)时会抛出interruptedException
        Thread.currentThread().interrupt();

        // 查询状态位
        System.out.println("Main t is interrupted ? " + Thread.currentThread().isInterrupted());

        // 清除状态位
        System.out.println("Main t is interrupted ? " + Thread.interrupted());
        // 清除状态位
        System.out.println("Main t is interrupted ? " + Thread.interrupted());

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            System.out.println("I'll be interrupted still.");
        }
    }

运行结果

Main t is interrupted ? false
Main t is interrupted ? false
Main t is interrupted ? true
Main t is interrupted ? true
Main t is interrupted ? false

可以看到并没有抛出异常执行到catch里的代码。

public static void main(String[] args){

        // 查询中断状态
        System.out.println("Main t is interrupted ? " + Thread.currentThread().isInterrupted());

        // 清除状态位
        System.out.println("Main t is interrupted ? " + Thread.interrupted());

        // 设置线程中断状态为true,执行阻塞方法()时会抛出interruptedException
        Thread.currentThread().interrupt();

        // 查询状态位
        System.out.println("Main t is interrupted ? " + Thread.currentThread().isInterrupted());

        // 清除状态位
//        System.out.println("Main t is interrupted ? " + Thread.interrupted());
        // 清除状态位
//        System.out.println("Main t is interrupted ? " + Thread.interrupted());

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            System.out.println("I'll be interrupted still.");
        }
    }

运行结果

Main t is interrupted ? false
Main t is interrupted ? false
Main t is interrupted ? true
I'll be interrupted still.

可以看到catch中的代码被执行了。

原因就在于我们在对线程进行中断之后调用Thread.interrupted()方法,该方法会先返回线程的当前中断状态,而后对中断状态进行重置。所以在前面贴的代码中interruptedException没有被抛出。

当我们将Thread.interrupted()方法注释后,发现interruptedException被抛出了。

 

可以看出静态方法interrupted()和成员方法isInterrupted()最大的区别在于:

静态方法先返回中断状态,再重置中断状态为false。

成员方法只返回中断状态,不对中断状态做任何其他操作。

你可能感兴趣的:(java高并发编程笔记)