我们如何在Java中停止线程?

每当我们想通过调用Java中的Thread 类的stop() 方法来停止线程的运行状态时,该方法将停止执行线程并从等待的线程池中将其删除并收集垃圾。当线程到达其方法的末尾时,它还将自动移动到死状态。将停止()方法被弃用 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.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;
   }
}

输出结果

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