专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java结束线程的方法

Java结束线程的方法

更新时间:2022-12-14 11:27:23 来源:星辉 浏览929次

每当我们想通过调用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

以上就是关于“Java结束线程的方法”,如果大家想了解更多相关知识,可以关注一下本站的多线程教程,里面还有更丰富的知识等着大家去学习,希望对大家能够有所帮助哦。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>