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

How do we stop a thread in Java?

WBOY
Release: 2023-09-13 17:21:03
forward
1107 people have browsed it

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()
Copy after login

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;
   }
}
Copy after login

Output

main is stopping user thread
The user thread is running
The user thread is now stopped
main is finished now
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template