How can we stop a thread in Java?

JavaObject Oriented ProgrammingProgramming

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java.This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method. The stop() method is deprecated in Java due to thread-safety issues.

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.stop();
      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
raja
Published on 05-Sep-2019 13:05:51
Advertisements