在java中有以下3种方法可以终止正在运行的线程:

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
  2. 使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法。

因为stop不安全:stop会解除由线程获取的所有锁定,当在一个线程对象上调用stop()方法时,这个线程对象所运行的线程就会立即停止,假如一个线程正在执行:synchronized void { x = 3; y = 4;} 由于方法是同步的,多个线程访问时总能保证x,y被同时赋值,而如果一个线程正在执行到x = 3;时,被调用了 stop()方法,即使在同步块中,它也会马上stop了,这样就产生了不完整的残废数据。

  1. 使用interrupt方法中断线程。

    interrupt状态停止线程 和 抛出异常停止线程

    调用interrupt方法是在当前线程中打了一个停止标志,并不是真的停止线程。

    1. 判断线程是否停止状态

    Thread.java类中提供了两种方法:

  2. this.interrupted():

测试当前线程是否已经中断;

  1. this.isInterrupted():

测试线程是否已经中断;

  1. public class MyThread extends Thread {
  2. public void run(){
  3. super.run();
  4. for(int i=0; i<500000; i++){
  5. if(this.interrupted()) {
  6. System.out.println("线程已经终止, for循环不再执行");
  7. return;
  8. // 或者,抛出异常
  9. // throw new InterruptedException();
  10. }
  11. System.out.println("i="+(i+1));
  12. }
  13. }
  14. }
  15. public class Run {
  16. public static void main(String args[]){
  17. Thread thread = new MyThread();
  18. thread.start();
  19. try {
  20. Thread.sleep(2000);
  21. thread.interrupt();
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }


i=202053
i=202054
i=202055
i=202056
线程已经终止, for循环不再执行

image.png