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 类的实例方法,测试调用该方法的线程是否已被中断,不会清除调用者线程的中断标志
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值