Java多线程中的Interrupt简析
Interrupt系列
在调用如下方法进行阻塞的线程,都可以调用该线程的interrupt()方法打断其阻塞
- Object的wait方法
- Thread的sleep方法
- Thread的join方法
- InterruptibleChannel的io操作
- Selector的wakeup方法
上述方法统称为可中断方法,实际上,能抛出InterruptedException异常的方法都是可中断方法
interrupt()方法
//源码
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}当一个线程被别的线程调用它的阻塞方法时,它会调用interrupt0()设置一个中断标识,如果被interrupt的线程正在阻塞状态,该线程的阻塞状态会被中断并且中断标识被清除,如例一
//例一
package online.hengtian.Thread;
import java.util.concurrent.TimeUnit;
public class InterruptDemo {
public static void main(String[] args){
Thread t1=new Thread(()->{
int i=0;
while(i<5){
System.out.println(i+" : 我当前的中断状态"+Thread.currentThread().isInterrupted());
try {
TimeUnit.SECONDS.sleep(1);
System.out.println(i+" : 我没被中断");
} catch (InterruptedException e) {
System.out.println("我被中断了");
System.out.println(i+" : 此时我的中断状态是"+Thread.currentThread().isInterrupted());
}
i++;
}
});
t1.start();
t1.interrupt();
}
}输出
0 : 我当前的中断状态true
我被中断了
0 : 此时我的中断状态是false
1 : 我当前的中断状态false
1 : 我没被中断
2 : 我当前的中断状态false
2 : 我没被中断
3 : 我当前的中断状态false
3 : 我没被中断
4 : 我当前的中断状态false
4 : 我没被中断
如果被interrupt的线程并没有进入阻塞状态,该线程在进入阻塞状态后会立即被中断,然后清除中断状态,测试如下:
//当线程被interrupt之后才会进入sleep方法
package online.hengtian.Thread;
import java.util.concurrent.TimeUnit;
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(()->{
//changed beginning
while(!Thread.currentThread().isInterrupted()){
System.out.println("我当前没被中断");
}
//changed end
int i=0;
while(i<5){
System.out.println(i+" : 我当前的中断状态"+Thread.currentThread().isInterrupted());
try {
TimeUnit.SECONDS.sleep(1);
System.out.println(i+" : 我没被中断");
} catch (InterruptedException e) {
System.out.println("我被中断了");
System.out.println(i+" : 此时我的中断状态是"+Thread.currentThread().isInterrupted());
}
i++;
}
});
t1.start();
TimeUnit.SECONDS.sleep(2);
t1.interrupt();
}
}截取部分输出如下
我当前没被中断
我当前没被中断
我当前没被中断
我当前没被中断
我当前没被中断
我当前没被中断
我当前没被中断
我当前没被中断
0 : 我当前的中断状态true
我被中断了
0 : 此时我的中断状态是false
1 : 我当前的中断状态false
1 : 我没被中断
2 : 我当前的中断状态false
2 : 我没被中断
3 : 我当前的中断状态false
3 : 我没被中断
4 : 我当前的中断状态false
4 : 我没被中断
当理解了interrupt方法中断的根本原因是中断标识之后,一切都会变的很简单
到此这篇关于Java多线程中的Interrupt简析的文章就介绍到这了,更多相关Java的Interrupt内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
如何在 Spring Boot 中配置和使用 CSRF 保护
CSRF是一种网络攻击,它利用已认证用户的身份来执行未经用户同意的操作,Spring Boot 提供了内置的 CSRF 保护机制,可以帮助您防止这种类型的攻击,这篇文章主要介绍了Spring Boot 中的 CSRF 保护配置的使用方法,需要的朋友可以参考下2023-09-09
详解java创建一个女朋友类(对象啥的new一个就是)==建造者模式,一键重写
这篇文章主要介绍了java建造者模式一键重写,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-04-04
SpringBoot+Maven 多模块项目的构建、运行、打包实战
这篇文章主要介绍了SpringBoot+Maven 多模块项目的构建、运行、打包实战,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-05-05


最新评论