当前位置:网站首页>Four methods of thread termination
Four methods of thread termination
2022-06-28 13:53:00 【Stars and dawn】
List of articles
End of normal operation
This is also the most common , Refers to the completion of thread body execution , Thread ends automatically .
Use the exit flag to exit
In general , stay run When the method is finished , The thread ends normally . However , Some threads are background threads , It takes a long time to run , Only after the system meets some special conditions , To exit these threads . You can use a variable to control the loop , For example, set up a Boolean Type of logo , And by setting this flag to true or false To control while Does the loop exit .
public class ThreadDemo extends Thread {
public volatile boolean exit = false;
@Override
public void run() {
while (!exit) {
// Business logic code
}
}
}
An exit representation is defined in the above code exit,exit The default value is false. In defining exit I used one Java Key words of volatile, This keyword is used to guarantee exit Thread synchronization is safe , That is, only one thread can modify at a time exit Value , stay exit by true When ,while Loop exit , Thread termination .
Use Interrupt Method to terminate a thread
In the use of Interrupt Method when the thread is terminated , There are two cases
- Thread is blocked
for example : In the use of sleep、 Call the lock wait Or call socket Of receive、accept When waiting for the method , It will block the thread . In the calling thread interrupt When the method is used , Will throw out InterruptException abnormal , By catching exceptions in the code , And then through break Jump out of the condition monitoring cycle , End the execution of this thread . Usually many people think that just call interrupt Method will end the thread , This understanding is actually problematic , It must be captured first InterruptedException Pass after exception break Out of the loop , To end normally run Method .
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(" Execute task code , There is sleep");
Thread.sleep(1000);// The writing is abnormal , There is an error to throw an exception
} catch (InterruptedException e) {
e.printStackTrace();
break;// When an exception is caught , You can exit the loop
}
}
}
}

- The thread is in an unblocked state
At this time , Use isInterrupted Method to determine the interrupt flag of the thread to exit the loop . Calling interrupt Method time , The interrupt flag will be set to true, At this time, you cannot exit the thread immediately, but you need to perform the resource release operation before the thread terminates , Wait for the resources to be released before exiting the thread safely .
Use stop Method to terminate a thread
Use stop Method to terminate a thread is not safe
You can call directly in the program Thread.stop Method to force thread termination , But it's dangerous , It's like suddenly cutting off the power supply of your computer , Instead of ending normally , This may lead to some unpredictable consequences .
Use... In the program Thread.sleep Method to terminate the thread , The child thread of this thread will throw ThreadDeatherror error , And release all the locks held by the child thread lock , Locked code blocks are generally used to protect data consistency , If you're calling Thread.stop Method causes all locks held by the thread lock to be suddenly released, making the lock resources uncontrollable . The protected data may be inconsistent , When other threads use the corrupted data , It is possible that the program is running incorrectly , therefore , It is not recommended to terminate threads in this way .
边栏推荐
- 排序
- Luogu_ P1303 A*B Problem_ High precision calculation
- 行动诠释价值,城联优品韩董事长出席广东英德抗洪捐赠公益活动会
- How to design data visualization platform
- 《畅玩NAS》家庭 NAS 服务器搭建方案「建议收藏」
- Oracle cloud infrastructure extends distributed cloud services to provide organizations with greater flexibility and controllability
- Kubernetes in-depth understanding of kubernetes (I)
- 求解汉诺塔问题
- 3. Overall UI architecture of the project
- Kubernetes' in-depth understanding of kubernetes (II) declaring organizational objects
猜你喜欢

Votre Code parle? (1)

中国广电5G套餐来了,比三大运营商低,却没预期那么低

3、项目的整体UI架构

yii2编写swoole的websocket服务

Hubble database x a joint-stock commercial bank: upgrade the number management system of Guanzi, so that every RMB has an "ID card"

其他国产手机未能填补华为的空缺,苹果在高端手机市场已无对手

Pytorch model

BERT为何无法彻底干掉BM25??

CVPR再起争议:IBM中稿论文被指照搬自己承办竞赛第二名的idea

Nature子刊 | 绘制植物叶际菌群互作图谱以建立基因型表型关系
随机推荐
接雨水系列问题
你的代码会说话吗?(上)
Forecast and Analysis on market scale and development trend of China's operation and maintenance security products in 2022
Double buffer drawing
再談exception——异常拋出時會發生什麼?
A queue of two stacks
Rk3399 platform development series explanation (use part) pinctrl subsystem introduction - Video Introduction
MySQL slave error: "you cannot 'alter' a log table“
ArrayList源码解析
G : 最大流问题
木兰开放作品许可证1.0面向社会公开征求意见
程序员坐牢了,会被安排去写代码吗?
30 sets of JSP website source code collection "suggestions collection"
Action interprets value. The chairman of chenglian Youpin Han attended the Guangdong Yingde flood fighting donation public welfare event
China Radio and television 5g package is coming, lower than the three major operators, but not as low as expected
DevEco Studio 3.0编辑器配置技巧篇
n-queens problem
栅格矢量数据的裁剪
3、项目的整体UI架构
Make an ink screen electronic clock, cool!