当前位置:网站首页>Explication détaillée de la méthode d'interruption du fil
Explication détaillée de la méthode d'interruption du fil
2022-07-18 03:00:00 【Papillon blanc】
Comment mettre en pause un autre thread dans un thread?
Il n'est pas recommandé ici d'utiliserstopMéthodes,UtiliserstopMéthode bien que vous puissiez forcer un thread en cours d'exécution ou en attente,Mais utiliserstopC'est dangereux..stop La méthode tue vraiment le thread,Si le thread verrouille la ressource partagée,Alors quand il a été tué, il n'y a plus de chance de libérer la serrure, Aucun autre thread ne sera jamais en mesure d'obtenir la serrure
On peut utiliserinterruptMéthodes.En utilisant cette méthode,Ce n'est pas commestop.La méthode interrompt un thread en cours d'exécution,Mais le thread va continuer;Mais l'état d'interruption du thread est défini,Est défini àtrue,Le thread détecte ce marqueur d'interruption de temps en temps,Pour déterminer si le fil doit être interrompu(L'état d'interruption esttrue)
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);
// Décidez vous - même s'il faut arrêter l'opération sur place
if(interrupted) {
System.out.println(interrupted);
break;
}
}
}, "t2");
t2.start();
// Laissez le fil principal dormir
Thread.sleep(500);
t2.interrupt();
}
}
Résultats obtenus:
Mais quand nous interrompons Congestion(sleep,wait,join) Ce thread va produire un InterruptedExceptionAnomalie, Fin de l'exécution du thread . Mais si l'exception est saisie par le thread , Le thread peut encore décider du traitement ultérieur (Fin de l'opération,Continuez à courir, Faire des travaux de postcure, etc ), Et ce thread dans le blocage de rupture va Réinitialiser l'état de l'étiquette à 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;
// Démarrer le thread
public void start() {
monitor = new Thread(() -> {
while (true) {
//Obtenir le thread actuel
Thread thread = Thread.currentThread();
if(thread.isInterrupted()) {
// Appelez isInterrupted Obtenir la valeur de l'étiquette Celui - ci n'effacera pas la marque
System.out.println("Je m'occupe des affaires ...");
break; //Fil de terminaison
} else {
try {
Thread.sleep(1000);
System.out.println(" Effectuer des fonctions de surveillance ...");
} catch (InterruptedException e) {
System.out.println("Définir les marqueurs de rupture ...");
// Parce que la valeur de l'étiquette est devenue false, Encore une interruption , C'est comme casser ce fil en cours d'exécution , Donc la valeur de l'étiquette ici est redevenue ture, Si cette valeur n'est pas réinitialisée ici, le thread fonctionnera toujours
thread.interrupt();
e.printStackTrace();
}
}
}
}, "monitor");
monitor.start();
}
// Fil de terminaison
public void stop() {
monitor.interrupt();
}
}

À propos deisInterrupted()EtInterrupted()Méthodes
Les deux méthodes peuvent déterminer l'état de rupture du fil courant ,La différence est que:
interrupted()C'est une méthode statique, Et réinitialisera l'état d'interruption du fil courant (Toujoursfalse).EtisInterrupted() Ne pas réinitialiser l'état actuel
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("Première fois"+Thread.interrupted());
System.out.println("Deuxième fois"+Thread.interrupted());
}
}
Ici, nousinterruptC'estmainThread,Appelezinterrupted() La méthode sera réinitialisée à false
边栏推荐
猜你喜欢

Mqtt--- connect connection

How to choose the two tracks of shengteng AI innovation competition? Just take this introduction!

使用 Terraform 在阿里云上快速部署 MQTT 集群

【流放之路-第一章】

Introduction to risk assessment

Zhiyuan community weekly 89: Yann Lecun and other writers responded to Marcus' symbolic reasoning debate; Zhu Songchun's new work of aligning AI value with science's official website headlines; Ma Yi,

The end of kotlin plug-in and the rise of viewbinding

有奖调研 | openEuler 开发者体验调研问卷

Google recommends using kotlin flow in MVVM architecture

【云原生】基于Kubevela华为云的Terraform addon开发
随机推荐
Vector
Bc20 at command test
05 USART sending and receiving data (query mode)
2022年7月11日-2022年7月17日(ue4视频教程和文档)
Get started with pyGame
03 key control LED
It should be so simple. Databinding and viewbinding
使用 Terraform 在阿里云上快速部署 MQTT 集群
Spark中RDD、DataFrame和DataSet的区别与联系
「开源摘星计划」Harbor高可用集群设计及部署(实操+视频),基于离线安装方式
Alibaba cloud Internet of things platform construction
C language · bugs and Solutions
H5实现生成urlscheme并从H5跳转到小程序
从零实现深度学习框架——GloVe
马斯克中止推特收购,分手费10亿美元
Traverse the file (txt) under the folder and delete the last line
UMI 3.0 template
Getting started with esp8266 Lua
Fragment (IV) common problems
Configuration of teacher management module and MP automatic code generation