interrupt interrupted isInterrupted的区别
一、interrupt
1、interrupt用于中断其它线程,置其中断状态为true,但不会立刻使线程结束。
public static void main(String[] args) {
Thread aThread = new Thread(() -> {
System.out.println("a thread begin");
while (!Thread.currentThread().isInterrupted()) {
System.out.println("not interrupted");
}
while (Thread.currentThread().isInterrupted()){
System.out.println("interrupting");
}
});
aThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 调用a线程的interrupt()方法后,输出从not interrupted->interrupting,一直下去,证明只是改变状态,不会中断线程。中断线程可以由a线程自己根据状态值来执行中断操作。
aThread.interrupt();
}
2、如果线程已处于wait,join,sleep阻塞中,再调用interrupt方法,会抛InterruptedException,且中断状态置为false。
public static void main(String[] args) {
Thread aThread = new Thread(() -> {
System.out.println("a thread begin");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("catch InterruptedException");
System.out.println("status:"+Thread.currentThread().isInterrupted());
}
});
aThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
aThread.interrupt();
}
输出为:
a thread begin
catch InterruptedException
status:false
二、isInterrupted 和 interrupted的区别
两者都用于返回中断状态,isInterrupted不是静态方法,不会擦除状态,interrupted是静态方法,会擦除状态。
擦除状态指的是,返回当前状态值,再把状态值设置为false。如果多次调用interrupted方法(期间没有中断操作,即不会被调用interrupt方法),那么从第二次开始返回的值为false。
public static void main(String[] args) {
Thread aThread = new Thread(() -> {
System.out.println("a thread begin");
while (!Thread.currentThread().isInterrupted()) {
System.out.println("not interrupted");
}
while (Thread.interrupted()) {
System.out.println("interrupting");
}
});
aThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
aThread.interrupt();
}
解释:调用interrupt方法后,状态变为true。所以会打印interrupting,但是只会打印一次。因为第二次调用interrupted时,返回的值被上次重置为false。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南