Java 如何停止一个线程

Java 如何停止一个线程

当我们想要通过调用Java中Thread类的stop()方法来停止一个线程时,该方法会停止正在运行的线程的执行并将其从等待线程池中移除,并进行垃圾回收。当一个线程到达其方法的末尾时,它也会自动转移到dead状态。由于线程安全问题,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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程