isInterrupted()方法和interrupted()方法简析

先看看二者的方法源码:

isInterrupted()方法:

  //这里的false代表着获取到中断标志后不重置中断标志
  public boolean isInterrupted() {
        return isInterrupted(false);
    }
//获取中断标志   
private native boolean isInterrupted(boolean ClearInterrupted);

interrupted()方法:

 //可以看到这个方法以当前线程为参数,调用了isInterrupted()方法来获取中断标志,不过参数是true,所以会重置中断标志
 public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
//获取当前线程    
public static native Thread currentThread();
//获取中断标志
private native boolean isInterrupted(boolean ClearInterrupted);

从代码层面,我们可以推测,isInterrupted()方法获取的结果和具体调用这个方法的线程对象有关,而interrupted()方法则不同,它是静态方法,调用对象是固定用currentThread()方法去获取的当前线程对象,而不是具体的调用线程对象。

代码示例

public class TestMain {

    private static volatile boolean tag = false;

    public static void main(String[] args) throws Exception {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程一开始运行");
                for (; ; ) {
                    //跳出循环
                    if (tag) {
                        break;
                    }
                }
            }
        });
        //开启线程
        thread1.start();
        //设置中断标志
        thread1.interrupt();
        //获取中断标志
        System.out.println("thread1的isInterrupted()方法结果" + thread1.isInterrupted());
        //获取中断标志并重置
        System.out.println("thread1的interrupted()方法结果" + thread1.interrupted());
        //获取中断标志并重置
        System.out.println("Thread的interrupted()方法结果" + Thread.interrupted());
        //获取中断标志
        System.out.println("thread1的isInterrupted()方法结果" + thread1.isInterrupted());
        //标记位设置成true
        tag = true;
        //等待线程一运行结束
        thread1.join();
        //主线程运行结束
        System.out.println("主线程结束运行");
    }
}

运行结果:
在这里插入图片描述

从运行结果可以看出,thread1设置了中断标记,所以第一句获取thread1的中断标记,结果自然是true。interrupted()方法底层还是由当前线程来调用的,而当前主线程并没有设置中断标记,所以第二句结果是false。第三句和第二句其实是一样的,都是返回当前线程的中断标记,由于没有设置过,自然还是返回false。第4句由于thread1其实只调用了isInterrupted()方法,不会重置中断标记,所以结果不变,还是false。

总结

哪个线程对象调用了isInterrupted()方法,返回的就是这个线程对象的中断标记,而且中断标记不会被重置。而不管哪个线程对象调用了interrupted()方法,真正调用它的其实还是当前线程,同时这个方法在返回中断标记结果后还会重置中断标记。

发布了217 篇原创文章 · 获赞 215 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/104550177