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.
@Deprecated public final void stop()
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; } }
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!