interrupt和interrupted和isInterrupted的区别
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11413917.html
interrupt
Code Demo
1 package org.fool.thread; 2 3 public class InterruptTest1 { 4 public static void main(String[] args) { 5 Thread thread = new Thread(new Runnable() { 6 @Override 7 public void run() { 8 for (int i = 0; i < 100000; i++) { 9 System.out.println(Thread.currentThread().getName() + " i = " + i); 10 } 11 } 12 }); 13 14 thread.start(); 15 16 thread.interrupt(); 17 } 18 }
Note:
从运行结果来看,调用interrupt方法并没有停止线程
interrupted
Code Demo
1 package org.fool.thread; 2 3 public class InterruptTest2 { 4 public static void main(String[] args) { 5 Thread thread = new Thread(() -> { 6 for (int i = 0; i < 10; i++) { 7 System.out.println(Thread.currentThread().getName() + " i = " + i); 8 9 if (i == 5) { 10 Thread.currentThread().interrupt(); 11 12 System.out.println("interrupted 1: " + Thread.interrupted()); 13 14 System.out.println("interrupted 2: " + Thread.interrupted()); 15 } 16 } 17 }); 18 19 thread.start(); 20 21 } 22 }
Console Output
Note:
控制台第一次打印的结果是true,第二次为false;Java Doc中给出的解释是:测试当前线程是否已经中断,线程的中断状态由该方法清除。即如果连续两次调用该方法,则第二次调用将返回false(在第一次调用已清除flag后以及第二次调用检查中断状态之前,当前线程再次中断的情况除外)
所以,interrupted()方法具有清除状态flag的功能
isInterrupted
Code Demo
1 package org.fool.thread; 2 3 public class InterruptTest3 { 4 public static void main(String[] args) { 5 Thread thread = new Thread(() -> { 6 for (int i = 0; i < 10; i++) { 7 System.out.println(Thread.currentThread().getName() + " i = " + i); 8 } 9 }); 10 11 thread.start(); 12 13 // main thread interrupt 14 Thread.currentThread().interrupt(); 15 16 System.out.println(thread.getName() + ":" + thread.isInterrupted()); 17 System.out.println(thread.getName() + ":" + thread.isInterrupted()); 18 System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted()); 19 System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted()); 20 21 // thread interrupt 22 thread.interrupt(); 23 24 System.out.println(thread.getName() + ":" + thread.isInterrupted()); 25 System.out.println(thread.getName() + ":" + thread.isInterrupted()); 26 } 27 }
Console Output
Summary
调用interrupt()方法仅仅是在当前线程中打了一个停止的标记,并不是真正的停止线程
interrupted()测试当前线程是否已经是中断状态,执行后具有清除中断状态flag的功能
isInterrupted()测试线程Thread对象是否已经是中断状态,但不清除中断状态flag
强者自救 圣者渡人
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构