interrupt和interrupted和isInterrupted的区别
2024-08-25 12:21:38
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11413917.html
interrupt
Code Demo
package org.fool.thread; public class InterruptTest1 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
System.out.println(Thread.currentThread().getName() + " i = " + i);
}
}
}); thread.start(); thread.interrupt();
}
}
Note:
从运行结果来看,调用interrupt方法并没有停止线程
interrupted
Code Demo
package org.fool.thread; public class InterruptTest2 {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " i = " + i); if (i == 5) {
Thread.currentThread().interrupt(); System.out.println("interrupted 1: " + Thread.interrupted()); System.out.println("interrupted 2: " + Thread.interrupted());
}
}
}); thread.start(); }
}
Console Output
Note:
控制台第一次打印的结果是true,第二次为false;Java Doc中给出的解释是:测试当前线程是否已经中断,线程的中断状态由该方法清除。即如果连续两次调用该方法,则第二次调用将返回false(在第一次调用已清除flag后以及第二次调用检查中断状态之前,当前线程再次中断的情况除外)
所以,interrupted()方法具有清除状态flag的功能
isInterrupted
Code Demo
package org.fool.thread; public class InterruptTest3 {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " i = " + i);
}
}); thread.start(); // main thread interrupt
Thread.currentThread().interrupt(); System.out.println(thread.getName() + ":" + thread.isInterrupted());
System.out.println(thread.getName() + ":" + thread.isInterrupted());
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted()); // thread interrupt
thread.interrupt(); System.out.println(thread.getName() + ":" + thread.isInterrupted());
System.out.println(thread.getName() + ":" + thread.isInterrupted());
}
}
Console Output
Summary
调用interrupt()方法仅仅是在当前线程中打了一个停止的标记,并不是真正的停止线程
interrupted()测试当前线程是否已经是中断状态,执行后具有清除中断状态flag的功能
isInterrupted()测试线程Thread对象是否已经是中断状态,但不清除中断状态flag
最新文章
- Matlab中的向量
- ScrollVIew 边界阴影效果
- Centos 6.4 /usr/src/kernels 目录为空解决方法
- Node.js + Express + Mongodb 开发搭建个人网站(三)
- 关于对象和this、new
- windows简单杀死进程的批处理程序
- 磁盘管理之 raid 文件系统 分区
- Java I/O---类体系总结
- LAMP环境跟LNMP环境有什么不同,主要用什么地方
- 紧急求助!配置SMTP插件出错,SMTP connect() failed
- 操作系统内核Hack:(四)内核雏形
- 动态编程(Dynamic Programming)
- tiny png
- Python模块学习 - Paramiko
- 模拟数据库丢失undo表空间
- linux(kali,centos)安装vm及其提示缺少c头文件解决方法
- windows socket扩展函数
- MM bound 与 Jensen&#39;s inequality
- php分享二十四:数组
- Linux CentOS Python开发环境搭建教程
热门文章
- Redis Redis-Cell
- 测试单点登录xml配置
- 转:C++ 11 Lambda表达式
- 数据中 int 转 double 方式
- 1-什么是 Prometheus
- python中的单例模式及其实现
- 2018-2019 2 20165203 《网络对抗技术》Exp8 Web基础
- Exception in thread ";main"; java.lang.SecurityException: Invalid signature file digest for Manifest
- 洛谷P2387 [NOI2014]魔法森林(LCT)
- 时间复杂度为n^2的排序