Home  >  Article  >  Java  >  How do we stop a thread in Java?

How do we stop a thread in Java?

WBOY
WBOYforward
2023-09-13 17:21:031072browse

How do we stop a thread in Java?

Whenever we want to stop a running thread by calling the stop() method of the Thread class in Java, this method stops Execution of a running thread and removes it from the waiting thread pool and garbage collection. When a thread reaches the end of its method, it also automatically moves to the death state. Due to thread safety issues, the stop() method has been deprecated in Java.

Syntax

@Deprecated
public final void stop()

Example

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;
   }
}

Output

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

The above is the detailed content of How do we stop a thread in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete