如何在 Java 中停止一个线程?


每当我们想通过调用 Java 中Thread 类stop() 方法来停止一个线程的运行状态时,此方法会停止一个正在运行的线程的执行,并将其从等待线程池中移除并进行垃圾回收。一个线程也会在其方法的末尾时自动进入死状态。由于线程安全问题,在 Java 中stop() 方法已被弃用。

语法

@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 

更新于:01-Dec-2023

24K+ 次浏览

开启您的事业

完成课程以获得认证

开始
广告