Thread -- 10 -- interrupt()、interrupted()、isInterrupted()方法的区别

原文链接:Thread – 10 – interrupt()、interrupted()、isInterrupted()方法的区别


相关文章:


一、interrupt()

public void interrupt() {
    if (this != Thread.currentThread())
        checkAccess();

    synchronized (blockerLock) {
        Interruptible b = blocker;
        if (b != null) {
            interrupt0();           // Just to set the interrupt flag
            b.interrupt(this);
            return;
        }
    }
    interrupt0();
}
  • 当调用 interrupt() 方法时

    • 如果线程处于阻塞状态,那么线程将立刻退出阻塞状态,并抛出 InterruptedException 异常

    • 如果线程处于正常活动状态,那么会将该线程的中断标志设为 true,被设置了中断标志的线程会继续执行,不受影响,线程何时中断取决于线程本身


二、interrupted()

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

private native boolean isInterrupted(boolean ClearInterrupted);
  • 测试当前线程是否已被中断,同时清除当前线程的中断标志

  • 换句话说,如果连续调用两次该方法,则第二次调用将返回 false

  • 举例说明

    public static void main(String[] args) {
        System.out.println("Hello World");
        Thread.currentThread().interrupt();
        System.out.println(Thread.interrupted());
        System.out.println(Thread.interrupted());
    }
    
    // Hello World
    // true
    // false
    

三、isInterrupted()

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

private native boolean isInterrupted(boolean ClearInterrupted);
  • 测试调用该方法的线程是否已被中断,该方法不会清除调用其的线程的中断标志

  • 举例说明

    public static void main(String[] args) {
        Thread thread = new Thread(() -> System.out.println("Hello World"));
        thread.start();
        thread.interrupt();
        System.out.println(thread.isInterrupted());
        System.out.println(thread.isInterrupted());
    }
    
    // true
    // true
    // Hello World
    

四、归纳总结

  • interrupt()

    • Thread 类的实例方法,将调用该方法的线程的中断标志设置为 true,被设置了中断标志的线程会继续执行,不受影响,线程何时中断取决于线程本身
  • interrupted()

    • Thread 类的静态方法,测试当前线程是否已被中断,同时清除当前线程的中断标志
  • isInterrupted()

    • Thread 类的实例方法,测试调用该方法的线程是否已被中断,该方法不会清除调用其的线程的中断标志
posted @ 2020-05-17 19:15  GeneXu  阅读(80)  评论(0)    收藏  举报