Maison  >  Article  >  Java  >  Comment arrêter un thread en Java ?

Comment arrêter un thread en Java ?

WBOY
WBOYavant
2023-09-13 17:21:031037parcourir

Comment arrêter un thread en Java ?

Chaque fois que nous voulons arrêter un thread en cours d'exécution en appelant la méthode stop() de la classe Thread en Java, cette méthode arrête l'exécution du thread en cours d'exécution et le supprime du pool de threads en attente, supprimé et récupéré. Lorsqu’un thread atteint la fin de sa méthode, il passe également automatiquement à l’état mort. En raison de problèmes de thread safety, la méthode stop() a été obsolète en Java.

Syntaxe

@Deprecated
public final void stop()

Exemple

import static java.lang.Thread.currentThread;
public class ThreadStopTest {
   public static void main(String args[]) throws InterruptedException {
      UserThread userThread = new UserThread();
      Thread thread = new Thread(userThread, "T1");
      thread.start();
      System.out.println(currentThread().getName() + " is stopping user thread");
      userThread.<strong>stop()</strong>;
      Thread.sleep(2000);
      System.out.println(currentThread().getName() + " is finished now");
   }
}
class UserThread implements Runnable {
   private volatile boolean exit = false;
   public void run() {
      while(!exit) {
         System.out.println("The user thread is running");
      }
      System.out.println("The user thread is now stopped");
   }
   public void stop() {
      exit = true;
   }
}

Sortie

main is stopping user thread
The user thread is running
The user thread is now stopped
main is finished now

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer