线程的中断 - Interrupts

本文详细介绍了线程中断机制的工作原理及其应用。包括如何通过调用interrupt()方法来中断线程,以及如何处理InterruptedException来终止长时间运行的线程。此外还讨论了interrupt状态标志的作用。

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

Interrupt ?

An interrupt is an indication to a thread that it should stop what it is doing and do something else.

中断(interupt)是一个指示,指示一个线程停止正在做的事情,并做一些其他的事情。

我们通常使用 中断 去终止线程

如何中断线程 ?

调用 interrupt(),向线程发送 interrupt 指示。

如果一个线程内,频繁的调用一个可以 throw InterruptedException 的方法,在接收到 interrupt 指示时,抛出 InterruptedException 。只需要 catch 该异常,并 return,即可退出 run 方法 —— 即终止了线程。

for (int i = 0; i < importantInfo.length; i++) {
    // Pause for 4 seconds
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        // We've been interrupted: no more messages.
        return;
    }
    // Print a message
    System.out.println(importantInfo[i]);
}

Thread 的很多方法都可以 throw InterruptedException,比如 Thread.sleep 方法。当获取到 interrupt 指示时,这些方法将抛出异常。捕获这个异常,并 return ,即可中断线程。

如果一个线程会运行很长时间,且没有调用任何可以 throw InterruptedException 的方法,怎么办?必须定期运行 Thread.interrupted 方法,当获取 interrupt 指令时返回 true

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}

如果项目比较复杂的话,throw new InterruptedException 更有意义

if (Thread.interrupted()) {
    throw new InterruptedException();
}

中断状态标志 - The Interrupt Status Flag

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

interrupt 机制的实现,使用了一个内部的flag,用于标识 interrupt status 。

调用 静态方法 Thread.interrupted(用于检查当前 Thread 是否 interrupt),interrupt status 会被清除。
调用 非静态方法 isInterrupted(用于一个 Thread 查询另一个 Thread 是否 interrupt),不会清除 interrupt status。

参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值