java多线程之interrupted()和isInterrupted()的区别(源码解读)

关于线程终止方法interrupt()

由于stop()方法已经过时和废弃,是之前JDK设计有缺陷的方法,所以我们一般使用interrupt()方法来终止线程,但是interrupt()方法并不像stop()方法那样暴力终止线程,通俗的说使用效果并没有for+break语句那样,马上就终止循环。调用interrupt()方法仅仅是在当前线程中打了一个停止的标记,并不是真正意义上的停止线程。我们先来看一个简单的示例:

public class InterruptDemo extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 500000; i++) {
            System.out.println("i=" + (i + 1));

        }
    }

    public static void main(String[] args) {
        try {
            InterruptDemo interruptDemo = new InterruptDemo();
            interruptDemo.start();
            //让线程休眠2秒
            Thread.sleep(2000);
            interruptDemo.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
    }
}

执行结果如下:
java多线程之interrupted()和isInterrupted()的区别(源码解读)_第1张图片
从运行结果来看,interrupt()方法并没有终止线程,所以我们需要java提供的2个方法interrupted()和isInterrupted()来判断它停止的标志从而能正确的终止线程。但是这2个方法是很容易混淆的,下面我们通过源码解读+测试小例子来把它们的区别和用法彻底搞清楚。

Thread.interrupted()和this.isInterrupted()的区别

判断线程是否是停止状态,java中的JDK提供了两种方法:

Thread.interrupted():测试当前线程是否已经中断
this.isInterrupted():测试线程是否已经中断

这两个方法有什么差别呢?我们先看下JDK源码:

/**
     * Tests whether the current thread has been interrupted.  The
     * interrupted status of the thread is cleared by this method.  In
     * other words, if this method were to be called twice in succession, the
     * second call would return false (unless the current thread were
     * interrupted again, after the first call had cleared its interrupted
     * status and before the second call had examined it).
     *
     * 

A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return true if the current thread has been interrupted; * false otherwise. * @see #isInterrupted() * @revised 6.0 */ public static boolean interrupted() { return currentThread().isInterrupted(true); } /** * Tests whether this thread has been interrupted. The interrupted * status of the thread is unaffected by this method. * *

A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return true if this thread has been interrupted; * false otherwise. * @see #interrupted() * @revised 6.0 */ public boolean isInterrupted() { return isInterrupted(false); } /** * Tests if some Thread has been interrupted. The interrupted state * is reset or not based on the value of ClearInterrupted that is * passed. */ private native boolean isInterrupted(boolean ClearInterrupted);

首先我们发现这个2个方法都调用了isInterrupted(boolean ClearInterrupted)这个方法,我们看这个方法的注解,它的意思是说如果一个线程已经被终止了,中断状态是否被重置取决于ClearInterrupted的值,即ClearInterrupted为true时,中断状态会被重置,为false则不会被重置。
然后我们比较这2个方法的差别,结果就很明显了,可以看出,interrupted()是静态方法,所以我们用Thread.interrupted()方法表示,它调用的是currentThread().isInterrupted(true)方法,即说明是返回当前线程的是否已经中断的状态值,而且有清理中断状态的机制。而isInterrupted()是一个实例方法,所以我们用this.isInterrupted()方法表示,它调用的是isInterrupted(false)方法,意思是返回线程是否已经中断的状态值,与Thread.interrupted()方法相反,它没有清理中断状态的机制。(PS:这里看不懂没关系,后面会用例子验证)

1. Thread.interrupted()

下面我们先研究一下Thread.interrupted()方法,请看下面的一个例子:

public class InterruptDemo1 extends Thread {

    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 50000; i++) {
            System.out.println("i=" + (i + 1));
        }
    }

    public static void main(String[] args) {
        InterruptDemo1 thread=new InterruptDemo1();
        thread.start();
        try {
            Thread.sleep(1000);
            thread.interrupt();
            System.out.println("是否已经停止 1?="+Thread.interrupted());
            System.out.println("是否已经停止 2?="+Thread.interrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end!");
    }

执行结果如下:
java多线程之interrupted()和isInterrupted()的区别(源码解读)_第2张图片

从执行的结果来看,线程并未终止,这也就证明了interrupted()方法的解释:测试当前线程是否已经中断,这个“当前线程”是main,它从未中断过,所以2个结果都是false。
哪如何让main线程终止呢?

public class InterruptDemo2 {
    public static void main(String[] args) {
        Thread.currentThread().interrupt();
        System.out.println("是否停止 1?="+Thread.interrupted());
        System.out.println("是否停止 2?="+Thread.interrupted());
        System.out.println("end!");
    }
}

执行结果如下:

是否停止 1?=true
是否停止 2?=false
end!

从执行结果来看,方法interrupted()的确能判断出当前线程是否是中断(停止)状态。第二个false是什么意思呢,这就验证了我们上面所说的中断状态清除的情况,就是说interrupted()会清除中断状态,如果连续2次调用该方法,则第二次会返回false值(在第一次调用已清除了中端状态之后,且第二次调用检验完中断状态之前,当前线程再次中断的情况除外)。

2. this.isInterrupted()
分析完Thread.interrupted()方法之后,我们下面再来分析this.isInterrupted()方法:

public class InterruptDemo3 extends Thread {

    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 50000; i++) {
            System.out.println("i=" + (i + 1));
        }
    }

    public static void main(String[] args) {
        InterruptDemo3 thread = new InterruptDemo3();
        thread.start();
        try {
            Thread.sleep(1000);
            thread.interrupt();
            System.out.println("是否已经停止 1?=" + thread.isInterrupted());
            System.out.println("是否已经停止 2?=" + thread.isInterrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

执行结果:

java多线程之interrupted()和isInterrupted()的区别(源码解读)_第3张图片

从结果看,2个值都为true,说明方法isInterrupted()并没有清除中断状态标志,和我们之前分析源码的结果一致。

总结

  • interrupted()是static方法,调用的时候要用Thread.interrupted(),而isInterrupted()是实例方法,调用时要用线程的实例调用;
  • Thread.interrupted():测试当前线程是否已经是中断状态,执行后具有将状态标志清除为false的功能;
  • this.isInterrupted():测试线程Thread对象是否已经是中断状态,但不清除状态标志。

参考

《java多线程编程核心技术》

你可能感兴趣的:(java)