源码查看Thread.interrupted()和Thread.currentThread().isInterrupted()区别

 

JAVA线程状态、线程START方法源码、多线程、JAVA线程池、如何停止一个线程等多线程问题

 

 

这两个方法有点容易记混,这里就记录一下源码。

 

Thread.interrupted()和Thread.currentThread().isInterrupted()区别

静态方法Thread.interrupted()源码如下:

public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

可以看到,静态方法内部,调用了currentThread()获取当前线程后调用非静态方法isInterrupted();

根据源码,看到的区别是在于给isInterrupted()方法传参为true或不传参。

 

非静态方法Thread.currentThread().isInterrupted()源码如下:

public boolean isInterrupted() {
        return isInterrupted(false);
    }

  

调用了isInterrupted(boolean ClearInterrupted)的有参方法:

/**
     * 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);

该方法先获取线程中断状态,然后在根据参数决定是否重置中断状态,true重置,false不重置。

 

简单总结下:
静态方法Thread.interrupted()获取线程中断状态后,会重置中断状态为false

非静态方法Thread.currentThread().isInterrupted()获取线程中断状态后,不会重置中断状态。

 

你可能感兴趣的:(源码查看Thread.interrupted()和Thread.currentThread().isInterrupted()区别)