Bonjour,
Je cherche comment chercher et arrêter un thread par son nom.
Ci dessous j'ai deux classes avec deux main.
La première lance un thread avec le nom "MyThread0".
La deuxième, utilisant l'api "commons-lang3", cherche ce thread par son nom et essaies de l’interrompre.
J'exécute MainTh1
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package com.threads; import java.util.Date; class MyThread extends Thread{ public MyThread(String name) { this.setName(name); } @Override public void run() { int i = 20; while(i > 0){ System.out.println("Thread ["+Thread.currentThread().getThreadGroup().getName()+" , "+this.getId()+" , "+ this.getName()+"] :" + new Date()+ " Boucle infinie !"); } } } public class MainTh1 { public static void main(String[] args) { MyThread m = new MyThread("MyThread0"); m.start(); } }
J'exécute MainTh2
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package com.threads; import java.util.Collection; import org.apache.commons.lang3.ThreadUtils; public class MainTh2 { public static void main(String[] args) { Collection<Thread> liste = ThreadUtils.findThreadsByName("MyThread0"); System.out.println(liste.size()); if(liste!=null && !liste.isEmpty()){ for(Thread t : liste){ t.interrupt(); } } } }
MainTh2 ne trouve aucun thread avec le nom "MyThread0", alors qu'il est déjà en exécution (Boucle infinie).
Comment je peux arrêter mon thread à partir de MainTh2 ?
Merci pour votre retour.
Partager