关于java线程中的线程中断方法interrupt()

本文揭示了如何避免在使用Thread.interrupt()方法中断线程时的常见误区。关键在于目标线程需检查并响应中断,通过主动抛出InterruptedException。同时讨论了Thread.yield()方法在资源让渡中的微妙作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

偶然有一次看到这个方法并不推荐使用,去探究一波原因。

调用interrupt()方法,只是将目标线程的 interrupted status 置为 true ,并不会暂停当前线程。这依赖目标线程的后续处理,假如没有处理,将不会出现期待的效果。要想中断线程,需要目标线程用 Thread.interrupted() 方法检查 interrupted status ,当状态为 true 时,应主动执行清理,并且抛出 InterruptedException 异常。
注: Thread.interrupted() 方法会清理状态(重置为 false ),而 Thread.currentThread.isInterrupted() 并不会清理状态,因此使用的时候要格外注意。

public static long runThread1(long max) throws InterruptedException { // 标注throws
    long result = 0L;
    for (long i = 0L; i < max; i++) {
        result += i;
        if (Thread.interrupted()) { // 重点:周期性检查自己是否被interrupt
            throw new InterruptedException("Interrupted during summing"); // 主动中止
        }
    }
    return result;
}

public static void main(String[] args) throws Exception {
    Thread thread1 = new Thread(() -> {
        try {
            long result = runThread1(100000000L);
            LOGGER.log(result);
        } catch (InterruptedException ex) {
            // 线程顶层方法,实现Runnable,不处理,正常中止。
            LOGGER.log("worker thread stopped"); // 可以记录日志。
        }
    }, "meaningful-name");
    thread1.start();
    Thread.sleep(1000);
    thread1.interrupt(); // 用interrupt()方法请求中止
    thread1.join();
}

附带:Thread.yield() 方法的作用是暗示调度器收回目标线程的cpu资源,不一定会执行。如果执行了,效果就是目标线程放弃cpu资源,回归就绪态,重新与其他就绪状态的线程抢夺cpu资源。言外之意就是,我得到很多了,也给其他人一个“公平竞争”的机会。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值