InterruptedException与interrupt()方法简单说明
InterruptedException在如下场景下会发生,即使用sleep(),wait(),join()方法时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.java.test.Interrupted.expection; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; /** * @Description: * @Author: Yourheart * @Create: 2022/10/26 11:01 */ @Slf4j public class ThreadTest extends Thread{ @Override public void run() { try { Thread.sleep( 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.java.test.Interrupted.expection; /** * @Description: * @Author: Yourheart * @Create: 2022/10/26 10:54 */ public class InterruptedTest { public static void main(String[] args) throws InterruptedException { ThreadTest threadTest = new ThreadTest(); threadTest.start(); Thread.sleep( 10 ); threadTest.interrupt(); Thread.sleep( 100 ); System.exit( 0 ); } } |
能够被中断的阻塞为轻量级阻塞,对应的线程状态为WAITING或者TIMED)WAITING
像synchronized不能被中断的阻塞称为重量级阻塞,对应的状态为BLOCKED
线程在创建完成后,会进入RUNNING和READY两种状态,当调用阻塞函数(wait,join,park,sleep)后,线程根据不同的情况进入两种不同的状态,一种是WAITING,另一种是TIMED_WAITING,两者的不同之处在于,前者是无限阻塞,后者的阻塞是有时间限制的
因此thread.interrupt()的真实含义是唤醒轻量级的阻塞
下面给出thread.isInterrupted()和Thread.Interrupted()的区别,前者需要创建对象然后去调用,返回当前线程是否被中断了,只是获取状态值,不会重置线程的状态,后者是静态方法,会清除线程的状态
验证代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.java.test.Interrupted.expection; import lombok.extern.slf4j.Slf4j; /** * @Description * @Author qiuxie * @Date 2022/10/26 22:49 */ @Slf4j public class UpgradeThread extends Thread { @Override public void run() { int i = 0 ; while ( true ) { boolean interrupted = isInterrupted(); log.info( "中断标记:{}" ,interrupted); ++i; if (i > 200 ) { // 检查并重置中断标志。 boolean interrupted1 = Thread.interrupted(); log.info( "重置中断状态:{}" ,interrupted1); interrupted1 = Thread.interrupted(); log.info( "重置中断状态:{}" ,interrupted1); interrupted = isInterrupted(); log.info( "中断标记:{}" ,interrupted); break ; } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.java.test.Interrupted.expection; import lombok.extern.slf4j.Slf4j; /** * @Description * @Author qiuxie * @Date 2022/10/26 22:49 */ @Slf4j public class UpgradeTest { public static void main(String[] args) throws InterruptedException { UpgradeThread upgradeThread= new UpgradeThread(); upgradeThread.start(); Thread.sleep( 10 ); upgradeThread.interrupt(); Thread.sleep( 7 ); log.info( "中断状态检查-1:{}" ,upgradeThread.isInterrupted()); log.info( "中断状态检查-2:{}" ,upgradeThread.isInterrupted()); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异