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自定义配置属性源(PropertySource)
这篇文章主要介绍了Spring Boot自定义配置属性源(PropertySource),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-06-06
Java中Runnable和Callable的区别和联系及使用场景
Java多线程有两个重要的接口,Runnable和Callable,分别提供一个run方法和call方法,二者是有较大差异的,本文介绍Java中Runnable和Callable的区别和联系及使用场景,感兴趣的朋友一起看看吧2025-03-03
Java java.lang.InstantiationException异常案例详解
这篇文章主要介绍了Java java.lang.InstantiationException异常案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08
解决scala.collection.mutable.Map写入的问题
这篇文章主要介绍了解决scala.collection.mutable.Map写入的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06


最新评论