中断线程
来源:互联网 发布:如何修改淘宝店名 编辑:程序博客网 时间:2024/06/10 04:15
检查线程中断状态
每一个线程都有一个记录该线程中断状态的标记位,这是一个 boolean 标记。每个线程都应该不时地检查这个标记位以确定线程是否已经被中断。
调用 interrupt 方法可以请求终止线程,也就是将成功调用 interrupt 方法的线程的中断标记位置为 true。
如果我们想知道线程是否被置位,应该操作:
① 调用静态的 Thread.currentThread 方法获得当前线程
② 调用 isInterrupt 方法检查标记位
while(!Thread.currentThread().isInterrupt()){}
处于阻塞状态的线程,无法检查它的中断状态。如果试图检查阻塞线程的中断状态就会产生 InterruptedException 异常
interrupted 和 isInterrupted
有两个非常类似的方法 interrupted 和 isInterrupted, (interrupted 区别于interrupt方法,interrupt方法用来请求中断)
interrupted 方法是一个静态方法,它检测当前的线程是否被中断,而且调用 interrupted 方法后会清除该线程的中断状态,将当前线程中断状态位置为 false
isInterrupted 方法是一个实例方法,可以用来检测是否有线程被中断,调用这个方法不会改变线程的中断状态
不要忽略 InterruptedException
有两种方法处理 InterruptedException
1. 在 catch 子句中调用 Thread.currentThread().interrupt() 来设置中断状态
void Test(){ ... try { sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
2. 用 throws InterruptedException 标记方法
void Test() throws InterruptedException{ ... sleep(delay); ...}
阅读全文
0 0
- 线程中断
- 中断线程
- 中断线程
- 中断线程
- 中断线程
- 线程中断
- 中断线程
- 线程中断
- 中断线程
- 中断线程
- 中断线程
- 线程中断
- 线程中断
- 中断线程
- 线程中断
- 线程中断
- 线程中断
- 线程中断
- java原地归并排序(inplace)
- 好久没来CSDN了..
- Java反射机制
- hdu 4540 威威猫系列故事——打地鼠
- 给初学者的RxJava2.0教程(四)
- 中断线程
- Hive metastore三种配置方式
- go 使用 goroutine channel 通信
- 【整理】Cordova 从相册中选择照片/拍照并上传
- HDU 3172
- Java学习笔记-《Java程序员面试宝典》-第5章Java Web-5.3框架(5.3.9-5.3.10)
- NFC
- 【笔记】Nexus的使用
- CXF框架