Java多线程-停止线程

1、Java中终止正在运行线程的3中方法:

  1)run()方法完成后,正常终止

  2)使用 Thread.stop()强行终止

  3)使用 Thread.interrupt() 中断线程

 

2、Thread.stop()

  这个方法发可以停止一个线程,但是最好不用它,因为这个方法是不安全的,而且已经被弃用(被注解为 @Deprecated)

  stop()方法的缺陷:

  1)强制让线程停止,可能使一些清理性的工作得不到完成。

  2)对锁定的对象进行了“解锁”,导致数据得不到同步的处理,出现数据不一致的问题。

 

3、Thread.interrupt()

  直接调用不会终止正在运行的线程,需要加入一个判断才可以完成线程的停止。

  Thread.interrupt() 只是改变了当前线程的 interrupt 状态,并不是真的停止了当前线程的运行

  获取线程的 interrupt 状态有两个方法

  1)interrupted() 静态方法

  2)isInterrupted() 非静态方法

  区别:

  interrupted():获取当前线程的中断状态,执行后具有将状态标志清除为 false 的功能,所以连续两次调用 interrupted 第二次会输出 false

  isInterrupted(): 获取线程对象的中断状态,执行后,不清除中断状态

 

4、Thread.interrupt() 配合“异常法”停止线程

主要思想就是,获取到线程的中断状态为 true 之后,就抛出异常,结束线程代码块的执行

public class InterruptTest {
    public static void main(String[] args) {
        try {
            Thread thread = new MyThread();
            thread.start();
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 500000; i++) {
                if (this.isInterrupted()) {
                    System.out.println("已经是停止运行状态了!我要退出了!");
                    throw new InterruptedException();
                }
                System.out.println("i = " + (i + 1));
            }
        } catch (InterruptedException e) {
            System.out.println("进MyThread.java 类 run 方法中的 catch 了!");
            e.printStackTrace();
        }
    }
}

执行结果如下:

 

 

 

 

 

 

  

posted @ 2020-03-08 10:32  lkc9  阅读(168)  评论(0编辑  收藏  举报