Thread的interrupt、isInterrupted、interrupted源码探索

本文详细解析了Java中线程中断的实现机制,包括如何中断线程、中断的状态检查及清除方法。介绍了Thread类中的interrupt()方法的作用,以及isInterrupted()和interrupted()方法的区别和使用场景。

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

java.lang.Thread
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.//自己中断自己永远是可以的
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.//调用上述wait、join、sleep方法抛出InterruptedException异常后,中断状态会被清除,也就是中断状态是false
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.
If this thread is blocked in a java.nio.channels.Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.//中断没有alive的线程没有任何效果
Throws:

SecurityException - if the current thread cannot modify this thread




java.lang.Thread
public boolean isInterrupted()
Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.//测试这条线程是否被中断,中断状态不会变。但是interrupted会使中断状态由true转为false
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.
Returns:
true if this thread has been interrupted; false otherwise.
See Also:
interrupted()




java.lang.Thread
public static boolean interrupted()//interrupted结尾加ed表示过去式,让中断状态成为过去,假如当前线程已经是中断(true),让中断状态由true变为false
Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).//如果这个方法两次成功调用,那么第二次会返回false,因为第一次已经将中断状态由true变为false了。(除非在第一次调用和第二次调用之间,当前线程再一次执行Thread.currentThread.interrupt()方法)
A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.
Returns:
true if the current thread has been interrupted; false otherwise.
See Also:
isInterrupted()

### Java 中 `Thread.interrupt()`、`Thread.currentThread().isInterrupted()` 和 `Thread.interrupted()` 的区别 #### 1. **`Thread.interrupt()`** 该方法用于向目标线程发送一个中断信号,即将线程的中断状态设置为 `true`。如果目标线程正处于阻塞状态(如 `sleep` 或 `wait`),则会抛出 `InterruptedException` 并清除中断状态;如果是非阻塞状态,则仅设置中断标志而不触发任何异常。 示例代码如下: ```java public class InterruptExample { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> { while (true) { // 执行某些操作... } }); t.start(); Thread.sleep(1000); t.interrupt(); // 向线程发送中断信号 } } ``` 此方法的核心作用在于通知线程应该停止其当前活动[^1]。 --- #### 2. **`Thread.currentThread().isInterrupted()`** 这是一个静态方法,返回当前线程的中断状态 (`true` 表示已中断),但不会改变中断状态。它适用于需要多次检查中断状态而不想重置中断标志的情况。 以下是使用场景的一个例子: ```java public class IsInterruptedExample implements Runnable { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { System.out.println("Running..."); try { Thread.sleep(1000); // 模拟耗时任务 } catch (InterruptedException e) { Thread.currentThread().interrupt(); // 恢复中断状态 } } System.out.println("Thread Stopped"); } public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new IsInterruptedExample()); t.start(); Thread.sleep(3000); t.interrupt(); // 发送中断信号 } } ``` 在此案例中,`isInterrupted()` 负责持续监控线程的状态变化,直到接收到中断请求为止[^2]。 --- #### 3. **`Thread.interrupted()`** 这是另一种获取线程中断状态的方式,但它不仅读取还清除了当前线程的中断标志位。因此,在连续调用之间需谨慎处理以免丢失重要信息。 下面展示了一个简单的应用情形: ```java public class InterruptedExample { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> { while (true) { if (Thread.interrupted()) { // 检查并清除中断状态 System.out.println("Thread was interrupted, stopping."); break; } System.out.println("Still running..."); } }); t.start(); Thread.sleep(2000); t.interrupt(); // 请求终止子线程 } } ``` 这里需要注意的是每次调用都会消耗掉一次中断事件记录[^3]。 --- ### 总结对比表 | 特性/方法 | `Thread.interrupt()` | `Thread.currentThread().isInterrupted()` | `Thread.interrupted()` | |-------------------|-----------------------------------------|---------------------------------------------|----------------------------------------| | 功能 | 设置目标线程的中断状态 | 查询当前线程的中断状态 | 查询当前线程的中断状态并清除 | | 是否修改状态 | 是 | 否 | 是 | | 使用场合 | 唤醒阻塞线程或发出退出指令 | 需要反复判断是否被中断的情况下保持原样 | 只需一次性确认是否有过中断即可 | 以上即是对这三个函数特性的全面解析以及实际运用示范[^4][^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值