Java 学习笔记之 Sleep停止线程
2024-09-01 10:33:13
Sleep停止线程:
在Sleep状态下被interrupt,interrupted 状态会被擦除,返回false。
线程在Sleep状态下被interrupt:
public class SleepInterruptThread extends Thread{
@Override
public void run() {
try {
System.out.println("run begin");
Thread.sleep(2000000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("Interrupt in sleep stage. Interrupted status: " + this.isInterrupted());
e.printStackTrace();
}
}
} public class ThreadRunMain {
public static void main(String[] args) {
testSleepInterruptThread();
} public static void testSleepInterruptThread(){
try {
SleepInterruptThread sit = new SleepInterruptThread();
sit.start();
Thread.sleep(1000);
sit.interrupt();
} catch (InterruptedException e) {
System.out.println("Main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}
运行结果:
线程在Sleep之前被interrupt:
public class BeforeSleepInterruptThread extends Thread{
@Override
public void run() {
try {
for (int i=0;i<100000;i++){
System.out.println("i="+(i+1));
}
System.out.println("run begin");
Thread.sleep(2000000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("First interrupt, then sleep. Interrupted status: " + this.isInterrupted());
System.out.println("First interrupt, then sleep. Interrupted status: " + Thread.interrupted());
e.printStackTrace();
}
}
} public class ThreadRunMain {
public static void main(String[] args) {
testBeforeSleepInterruptThread();
} public static void testBeforeSleepInterruptThread(){
try {
BeforeSleepInterruptThread bsit = new BeforeSleepInterruptThread();
bsit.start();
Thread.sleep(100);
bsit.interrupt();
System.out.println("end!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
最新文章
- MYSQL、PHP基础、面向对象基础简单复习总结
- 04-c#入门(类型转换)
- C++ find 函数用法
- wex5 实战 二维码生成,扫描,蓝牙打印
- MySQL安装最后一步apply security settings错误
- 黄聪:Emeditor 编辑器常用的正则表达式
- POJ --- 2918 求解数独
- Currency System in Geraldion (Codeforces 560A)
- .haccess 配置生效
- angular访问后台服务及监控会话超时的封装
- Servlet实践--HelloWorld
- Android最火热修复实战
- 简单的做一个图片上传预览(web前端)
- c# 主窗体更新子窗体 进程间通信
- 关于iOS开发常用的一些东西
- Ubuntu下删除卸载程序图标
- QT的初步学习笔记
- rsync 实现文件同步 (重要数据通过rsyncr把数据同步到不同的两台服务器上,这样可以防止服务器的硬盘故障导致数据丢失) 客户端同步时如果要排某个目录
- Java中++,--,前缀后缀表达值的不同,与^的值计算
- bulid-tool