当前位置:网站首页>Detailed explanation of thread interrupt method
Detailed explanation of thread interrupt method
2022-07-18 03:00:00 【White butterfly】
How can we pause the running of another thread in one thread ?
It is not recommended to use stop Method , Use stop Method can forcibly terminate a running or suspended thread , But use stop The method is very dangerous .stop Method will really kill the thread , If the thread locks the shared resource , Then when it is killed, it will never have a chance to release the lock , Other threads will never acquire locks
We can use interrupt Method . When using this method , It's not like stop Method will interrupt a running thread , Instead, the thread will continue to run ; But the interrupt state of the thread will be set , It is set to true, The thread will detect this interrupt flag bit from time to time , To determine whether the thread should be interrupted ( Whether the interrupt status is true)
public class test2 {
public static void main(String[] args) {
try {
test2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void test2() throws InterruptedException {
Thread t2 = new Thread(()->{
while(true) {
Thread current = Thread.currentThread();
boolean interrupted = current.isInterrupted();
System.out.println(interrupted);
// Decide whether to stop the operation on site
if(interrupted) {
System.out.println(interrupted);
break;
}
}
}, "t2");
t2.start();
// Let the main thread sleep
Thread.sleep(500);
t2.interrupt();
}
}
Output results :
But when we interrupt Blocked (sleep,wait,join) The thread of will make this thread produce a InterruptedException abnormal , End the thread . But if the exception is caught by the thread , The thread can still decide the subsequent processing by itself ( Terminate run , Continue operation , Do some aftercare work and so on ), And the thread in the interrupt block will reset the flag state to false;
@Slf4j
public class test1 {
public static void main(String[] args) throws InterruptedException {
TwoParseTermination twoParseTermination = new TwoParseTermination();
twoParseTermination.start();
Thread.sleep(3500);
twoParseTermination.stop();
}
}
@Slf4j
class TwoParseTermination {
private Thread monitor;
// Start thread
public void start() {
monitor = new Thread(() -> {
while (true) {
// Get the current thread
Thread thread = Thread.currentThread();
if(thread.isInterrupted()) {
// call isInterrupted Get the tag value This will not clear the mark
System.out.println(" Take care of future affairs ...");
break; // Thread termination
} else {
try {
Thread.sleep(1000);
System.out.println(" Perform the function of monitoring ...");
} catch (InterruptedException e) {
System.out.println(" Set break flag ...");
// Because the tag value becomes false, Here's another interruption , It is equivalent to interrupting the running thread , So the tag value here becomes ture, If the tag value is not reset here, the thread will always run
thread.interrupt();
e.printStackTrace();
}
}
}
}, "monitor");
monitor.start();
}
// Thread termination
public void stop() {
monitor.interrupt();
}
}

About isInterrupted() and Interrupted() Method
Both of these methods can determine the interruption state of the current thread , The difference lies in :
interrupted() It's a static method , And reset the interrupt status of the current thread ( still false). and isInterrupted() The current state will not be reset
public class test2 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(100 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
thread.interrupt();
Thread.currentThread().interrupt();
System.out.println(" for the first time "+Thread.interrupted());
System.out.println(" The second time "+Thread.interrupted());
}
}
Here we are interrupt 了 main Threads , call interrupted() The method will be reset to false
边栏推荐
- The difference between the elements dependencies and dependencymanagement
- 08 use timer to control LED flashing
- After downloading pyqt5, I found that the designer could not be found Exe problem solution
- Why is it difficult for girls to learn programming? Is it the wrong way of thinking or the wrong way of learning?
- HCIP回顾(1)
- Introduction to esp8266 Lua (II)
- 使用KiCad插件,将PCB焊接可视化
- 仓储系统亮灯分拣
- 【云原生】基于Kubevela华为云的Terraform addon开发
- Hcip review (2)
猜你喜欢

Adding an index by Oracle causes other users to lose their query permissions on this table

10分钟带你进入Swagger的世界,快来看一看吧

MQTT---SUBSCRIBE和SUBACK

基础概念

Meta宣布推出Make-A-Scene:可基于文字和草图控制AI图像生成

08 use timer to control LED flashing

解决中小型机房动环状态综合监控方案

C language · function

07 printf redirection

Event preview | Apache Doris x Apache seatunnel joint meetup to start registration!
随机推荐
CCF 202012-1 期末预测之安全指数
使用KiCad插件,将PCB焊接可视化
谷歌提出可靠性机器学习模型Plex:让大模型对分布外数据提出合适的预测结果
送你的代碼上太空,與華為雲一起開發'最偉大的作品'
RobotFramework进阶(一)集成Pycharm及UI自动化用例编写
Xpath实战之爬取学习猿地的猿著(上)
ESP8266 lua入门
MQTT---SUBSCRIBE和SUBACK
基础概念
558. Quadtree intersection / Sword finger offer II 118 Redundant edge
实现意识的远程直接电磁通信,东大团队联合新加坡国大等构建电磁脑机超表面,有望成为全新通信范式
解决中小型机房动环状态综合监控方案
基于eTS高效开发HarmonyOS课程类应用
Safety index of CCF 202012-1 period end forecast
Web3离爆发还差什么?
「开源摘星计划」Harbor高可用集群设计及部署(实操+视频),基于离线安装方式
有奖调研 | openEuler 开发者体验调研问卷
Vector
女生学编程为什么难?是思维方式不对还是学习方式不对?
两个CVE漏洞复现