Java多线程之interrupt

interrupt()只是改变中断状态,不会中断一个正在运行着的线程。

线程被Object.wait、Thread.join、Thread.sleep三种方法之一阻塞,调用interrupt()方法会抛出异常InterruptException,结束阻塞状态。

线程没有被阻塞,调用interrupt()方法将不起作用。

// 中断线程

void interrupt();

// 检查线程是否被中断。如果该线程已经中断,则返回 true;否则返回 false。

boolean isInterrupted();

// 检查线程是否被中断,调用后会清除中断状态。如果该线程已经中断,则返回 true;否则返回 false。

//如果连续两次调用该方法,则第二次调用将返回 false(在第一次调用已清除了其中断状态之后,且第二次调用检验完中断状态前,当前线程再次中断的情况除外)。

static boolean interrupted();

 调用interrupt()中断方法时,会将interrupted设置为true

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

            // thread may be blocked in an I/O operation
            synchronized (blockerLock) {
                Interruptible b = blocker;
                if (b != null) {
                    interrupted = true;
                    interrupt0();  // inform VM of interrupt
                    b.interrupt(this);
                    return;
                }
            }
        }
        interrupted = true;
        // inform VM of interrupt
        interrupt0();
    }

 调用static boolean interrupted()方法时,如果interrupted为true,会将interrupted设置为false

    // 源码
    public static boolean interrupted() {
        Thread t = currentThread();
        boolean interrupted = t.interrupted;
        // We may have been interrupted the moment after we read the field,
        // so only clear the field if we saw that it was set and will return
        // true; otherwise we could lose an interrupt.
        if (interrupted) {
            t.interrupted = false;
            clearInterruptEvent();
        }
        return interrupted;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈年小趴菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值