当前位置:网站首页>Interview shock 26: how to stop threads correctly?
Interview shock 26: how to stop threads correctly?
2022-06-11 15:14:00 【Wang Lei】
stay Java The implementation methods of stopping threads in are as follows 3 Kind of :
Custom interrupt identifier , Stop thread . Use thread interrupt method interrupt Stop thread . Use stop Stop thread .
among stop Method is @Deprecated Expiration method of decoration , That is, the deprecated expiration method , because stop Method will directly stop the thread , In this way, the thread is not given enough time to process the saved work before stopping , It will cause the problem of incomplete data , Therefore, it is not recommended to use . and There are also some problems with custom interrupt identification , So in general ,interrupt Method is the most ideal way to stop threads , Next, let's look at their specific differences .
1. Custom interrupt identifier
Custom interrupt identifier is to define a variable in the program to determine whether the thread should interrupt execution , The specific implementation code is as follows :
class FlagThread extends Thread {
// Custom interrupt identifier
public volatile boolean isInterrupt = false;
@Override
public void run() {
// If true -> Interrupt execution
while (!isInterrupt) {
// Business logic processing
}
}
}
but The problem with customizing interrupt identifiers is : Thread interruption is not timely enough . Because the thread is executing , Unable to call while(!isInterrupt) To determine whether the thread is terminated , It can only determine whether to terminate the current thread at the next run , So it doesn't interrupt the thread in time , For example, the following code :
class InterruptFlag {
// Custom interrupt identifier
private static volatile boolean isInterrupt = false;
public static void main(String[] args) throws InterruptedException {
// Create interruptible thread instances
Thread thread = new Thread(() -> {
while (!isInterrupt) { // If isInterrupt=true Then stop the thread
System.out.println("thread Execution steps 1: The thread is about to go to sleep ");
try {
// Sleep 1s
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread Execution steps 2: The thread executes the task ");
}
});
thread.start(); // Start thread
// Sleep 100ms, wait for thread The thread runs
Thread.sleep(100);
System.out.println(" The main thread : An attempt was made to terminate the thread thread");
// Modify interrupt identifier , Interrupt threads
isInterrupt = true;
}
}
The execution result of the above code is shown in the figure below :
What we expect is : The thread executes step 1 after , Received instruction to interrupt thread , Then don't perform any more steps 2 了 , However, it can be seen from the above implementation results , Using a custom interrupt identifier is not possible to achieve our expected results , This is the custom interrupt identifier , The problem of not responding in time .
2.interrupt Interrupt threads
Use interrupt Method can be given to the thread executing the task , Send an instruction to interrupt the thread , It does not interrupt the thread directly , Instead, it sends a signal to interrupt the thread , Leave the initiative of whether the thread is being interrupted to the coder . Compared with the custom interrupt identifier , It can receive interrupt instruction in time , As shown in the following code :
public static void main(String[] args) throws InterruptedException {
// Create interruptible thread instances
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("thread Execution steps 1: The thread is about to go to sleep ");
try {
// Sleep 1s
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("thread Thread received interrupt instruction , Execute interrupt operation ");
// Interrupt the task execution of the current thread
break;
}
System.out.println("thread Execution steps 2: The thread executes the task ");
}
});
thread.start(); // Start thread
// Sleep 100ms, wait for thread The thread runs
Thread.sleep(100);
System.out.println(" The main thread : An attempt was made to terminate the thread thread");
// Modify interrupt identifier , Interrupt threads
thread.interrupt();
}
The execution result of the above code is shown in the figure below :
As can be seen from the above results , After the thread receives the interrupt instruction , Immediately interrupted the thread , Compared with the previous method of customizing interrupt identifier , It can respond to interrupt thread instructions in a more timely manner .
3.stop Stop thread
stop Method can stop the thread , But it is already an obsolete method that is not recommended , This can be done through Thread Class ,stop Source code is as follows :
As can be seen from the picture above ,stop The way is to be @Deprecated Modified deprecated expiration method , And the first sentence of the note shows stop The method is not safe . In the latest version Java in , This method has been removed directly , Therefore, it is strongly not recommended to use .
summary
This article introduces the method of stopping threads 3 Methods :
Stop method of custom interrupt identifier , The disadvantage of this method is that it can not respond to the interrupt request in time ; Use interrupt Interrupt thread method , This method sends an interrupt signal to the thread , It can respond to interruptions in a timely manner , It is also the most recommended method ; And finally stop Method , Although it can also stop threads , But this method is outdated and not recommended , stay Java The latest version has been removed directly , So it's not recommended .
It's up to you to judge right and wrong , Disdain is to listen to people , Gain or loss is more important than number .
official account :Java Analysis of the real interview questions
Interview collection :https://gitee.com/mydb/interview
边栏推荐
- Ali, tell me about the application scenarios of message oriented middleware?
- 02 _ 日志系统:一条SQL更新语句是如何执行的?
- 英伟达研发主管:AI 是如何改进芯片设计的?
- 中国技术出海,TiDB 数据库海外探索之路 | 卓越技术团队访谈录
- Illustration of tiger international quarterly report: revenue of USD 52.63 million continued to be internationalized
- 基于 GateWay 和 Nacos 实现微服务架构灰度发布方案
- Explain the kubernetes package management tool Helm
- Flower shop window (linear DP)
- 详解 Kubernetes 包管理工具 Helm
- 05 _ 深入浅出索引(下)
猜你喜欢

Illustration of tiger international quarterly report: revenue of USD 52.63 million continued to be internationalized

Uniapp développe des applets Wechat, de la construction à la mise en ligne

Implementation of the function of recording login status

05 _ 深入浅出索引(下)

uniapp开发微信小程序,从构建到上线

高数_第6章无穷级数__马克劳林级数

深度剖析「圈组」关系系统设计 | 「圈组」技术系列文章
![[azure application service] nodejs express + msal realizes the authentication experiment of API Application token authentication (AAD oauth2 idtoken) -- passport authenticate()](/img/11/7262211654680512dae0a9a696740e.png)
[azure application service] nodejs express + msal realizes the authentication experiment of API Application token authentication (AAD oauth2 idtoken) -- passport authenticate()

Qualcomm WLAN framework learning (29) -- 6GHz overview

19. 二叉搜索树的插入删除修剪
随机推荐
MySQL用户权限总结【用户授权必会】
Learnopongl notes (IV) - Advanced OpenGL II
Oauth2的理解
How about art plus online school? Is it a new online organization?
02 Tekton Pipeline
多云安全合规扫描平台之RiskScanner
Uniapp développe des applets Wechat, de la construction à la mise en ligne
Backtracking / solution space tree permutation tree
老虎国际季报图解:营收5263万美元 持续国际化布局
做自媒体剪辑真的能挣钱吗?
CNCF survey in 2021: a year for kubernetes to cross the gap
Devil cold rice # 037 devil shares the ways to become a big enterprise; Female anchor reward routine; Self discipline means freedom; Interpretation of simple interest and compound interest
China's technology goes to sea, tidb database's overseas exploration road | interview with excellent technical team
2022质量员-市政方向-岗位技能(质量员)考试模拟100题及模拟考试
07 _ 行锁功过:怎么减少行锁对性能的影响?
05 _ 深入浅出索引(下)
MySQL user authority summary [user authorization required]
Arthas实践操作文档记录
How to do well in we media? Did you do these steps right?
基于STM32F1的开源小项目