2

Thread中interrupted()方法和isInterrupted()方法区别

 2 years ago
source link: https://yang295513.github.io/2020/04/12/Thread%E4%B8%ADinterrupted-%E6%96%B9%E6%B3%95%E5%92%8CisInterrupted-%E6%96%B9%E6%B3%95%E5%8C%BA%E5%88%AB/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

源代码对比

    public boolean isInterrupted() {
        return isInterrupted(false);
    }
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
  • isInterrupted是非静态的

  • interrupted是静态的,而且本质上是调用了当前线程中的isInterrupted 方法,不过传入了一个参数true

当我们调用线程停止方法interrupt()方法停止当前线程的时候他并没有停止,而是在做了一个标记,也就说这个标记说明当前线程已经停止了,但是实际上线程还没有停止。

interrupted()是静态方法:内部实现是调用的当前线程的isInterrupted(),并且会重置当前线程的中断状态

isInterrupted()是实例方法,是调用该方法的对象所表示的那个线程的isInterrupted(),不会重置当前线程的中断状态

public class Thread03 {
    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(200);
        Thread.currentThread().interrupt();//更改了中断为为true
        System.out.println(Thread.currentThread().isInterrupted());//直接返回true
        System.out.println(Thread.currentThread().isInterrupted());//直接返回true
        System.out.println(Thread.interrupted());//更改标志位状态为false,但是返回true
        System.out.println(Thread.interrupted());//返回false
        System.out.println(Thread.currentThread().isInterrupted());//直接返回true
    }
}
  • isInterrupted不会更改中断标志位
  • interrupted如果发现标志位和实际状态不一致就会更改其状态,并且返回原有状态
  • interrupted返回的是当前执行该方法的状态,isInterrupted返回的是该线程的状态。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK