当前位置:网站首页>线程终止的 4 种方式
线程终止的 4 种方式
2022-06-28 13:48:00 【星辰与晨曦】
正常运行结束
这个也是最常见的,指线程体执行完成,线程自动结束。
使用退出标志退出
在一般情况下,在 run 方法执行完毕的时候,线程会正常结束。然而,有些线程是后台线程,需要长时间运行,只有在系统满足某些特殊条件后,才能退出这些线程。这时可以使用一个变量来控制循环,比如设置一个 Boolean 类型的标志,并通过设置这个标志为 true 或 false 来控制 while 循环是否退出。
public class ThreadDemo extends Thread {
public volatile boolean exit = false;
@Override
public void run() {
while (!exit) {
//业务逻辑代码
}
}
}
在上面的代码中定义了一个退出的表示 exit,exit 的默认值为 false。在定义 exit 时使用了一个 Java 的关键字 volatile,这个关键字是用于保证 exit 线程同步安全的,也就是说在同一时刻只能有一个线程修改 exit 的值,在 exit 为true 的时候,while 循环退出,线程终止。
使用 Interrupt 方法终止线程
在使用 Interrupt 方法在终止线程的时候,是由两种情况的
- 线程处于阻塞状态
例如:在使用 sleep、调用锁的 wait 或者调用 socket 的 receive、accept 等方法的时候,会使线程处于阻塞状态。在调用线程的 interrupt 方法时,会抛出 InterruptException 异常,我们通过在代码中捕获异常,然后通过 break 跳出状态监测循环,结束这个线程的执行。通常很多人认为只要调用 interrupt 方法就会结束线程,这个理解其实是有问题的,一定是要先捕获 InterruptedException 异常后再通过 break 跳出循环,才能正常的结束 run 方法。
public class InterruptThread {
public static void main(String[] args) {
InterruptDemo thread = new InterruptDemo();
thread.start();
thread.interrupt();
}
}
class InterruptDemo extends Thread {
@Override
public void run() {
while (Thread.currentThread().isInterrupted()) {
try {
System.out.println("执行任务代码,出现了sleep");
Thread.sleep(1000);//写的异常,出现要抛出异常的错误
} catch (InterruptedException e) {
e.printStackTrace();
break;//在捕获到异常的时候,就可以退出循环了
}
}
}
}

- 线程处于未阻塞状态
在这个时候,使用 isInterrupted 方法判断线程的中断标志来退出循环。在调用 interrupt 方法的时候,中断标志会设置为 true,此时并不能立刻退出线程而是需要执行线程终止前的资源释放操作,等待资源释放完毕后方可安全退出该线程。
使用 stop 方法终止线程
使用 stop 方法终止线程是不安全的
在程序中可以直接调用 Thread.stop 方法来强制终止线程,但这是很危险的,就像突然把你的电脑电源断了,而不是正常结束,这样可能就会导致一些无法预测的后果。
在程序使用 Thread.sleep 方法终止线程的时候,该线程的子线程会抛出 ThreadDeatherror 错误,并且释放子线程锁持有的所有锁,加锁的代码块一般被用于保护数据的一致性,如果在调用 Thread.stop 方法后导致该线程锁持有的所有锁突然释放而使锁的资源不可控制。被保护的数据就可能出现不一致的情况,其他线程在使用这些被破坏的数据时,就有可能是程序运行错误,因此,并不推荐采用这种方式终止线程的。
边栏推荐
- From PDB source code to frame frame object
- Embedded design and development project - liquid level detection and alarm system
- Inftnews | technology giants accelerate their march into Web3 and metauniverse
- How about stock online account opening and account opening process? Is it safe to open a mobile account?
- 药物发现新方法,阿斯利康团队通过课程学习改进从头分子设计
- 锐捷交换机配置ssh password登录命令[通俗易懂]
- (原创)【MAUI】一步一步实现“悬浮操作按钮”(FAB,Floating Action Button)
- N皇后问题
- MySQL multi table joint query
- 895. longest ascending subsequence
猜你喜欢

Connected to rainwater series problems

yii2编写swoole的websocket服务

MySQL multi table joint query

How to design data visualization platform

APP冷热启动专项测试

公司领导说,个人代码超10个Bug就开除,是什么体验?

If a programmer goes to prison, will he be assigned to write code?

StackOverflow 2022数据库年度调查

How vscade sets auto save code

China Database Technology Conference (DTCC) specially invited experts from Kelan sundb database to share
随机推荐
公司领导说,个人代码超10个Bug就开除,是什么体验?
yii2编写swoole的websocket服务
To be the Italian Islander? Liuqiangdong cashed out 6.6 billion yuan in two months and made a one-time 560million "emergency transfer" to buy the European maritime Palace
Oracle cloud infrastructure extends distributed cloud services to provide organizations with greater flexibility and controllability
Unit test ci/cd
为什么新的5G标准将为技术栈带来更低的 TCO
嵌入式设计与开发项目-液位检测告警系统
Luogu_ P1303 A*B Problem_ High precision calculation
Notes on the use of official jeecg components (under update...)
Elastic box auto wrap demo
几百行代码实现一个 JSON 解析器
n-queens problem
Pytorch Foundation
Pytorch model parameter adjustment and training related contents
Double buffer drawing
How about stock online account opening and account opening process? Is it safe to open a mobile account?
Black apple installation tutorial OC boot "suggestions collection"
China Radio and television 5g package is coming, lower than the three major operators, but not as low as expected
Ruijie switch configuration SSH password login command [easy to understand]
原生JS 实现页面元素的拖动 拖拽