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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
package thread;
public class Thread_Arret_Altruiste implements Runnable {
public static void main(String[] args) {
Thread_Arret_Altruiste arret = new Thread_Arret_Altruiste();
Thread thread = new Thread(arret);
System.out.println("Démarrage du thread...");
thread.start();
System.out.println("thread.start(); a démarré");
try {
System.out.println("Thread en sommeil");
Thread.sleep(2000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// Arrêt du thread par une méthode dépréciée
System.out.println("Arrêt du thread");
thread.stop();
}
public void run() {
int compteur = 0;
System.out.println("Démarage du compteur");
while (true) {
System.out.println("Compteur = " + compteur);
compteur++;
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/*
* RESULTAT
Démarrage du thread...
thread.start(); a démarré
Thread en sommeil
Démarage du compteur
Compteur = 0
Compteur = 1
Compteur = 2
Compteur = 3
Compteur = 4
Compteur = 5
Compteur = 6
Compteur = 7
Compteur = 8
Compteur = 9
Compteur = 10
Compteur = 11
Compteur = 12
Compteur = 13
Compteur = 14
Compteur = 15
Compteur = 16
Compteur = 17
Compteur = 18
Compteur = 19
Compteur = 20
Arrêt du thread
*/ |
Partager