Java停止线程运行的三种方式

来源:互联网 发布:从元数据 编辑:程序博客网 时间:2024/05/19 21:17

Java终止正在运行的线程的方式有如下三种

  • 1 使用退出标志,使线程正常退出,也就是run方法完成后线程终止
  • 2 使用stop方法强行终止线程(已过时),但是不推荐使用这个方法
  • 3 使用interrupt方法中断线程

1 使用退出标志,使线程正常退出,也就是run方法完成后线程终止

当run方法正常执行完,线程也就停止了,当有循环时,可设置一个标志变量,为真时运行,否则退出循环,主要代码如下:

public void run() {    while(flag){        //do something    }}

想要终止运行时,只需设置flag值为false即可。

2 使用stop方法强行终止线程(已过时)

使用stop()方法能立即停止线程,但是可能使一些请理性工作得不到完成。另一种情况就是对锁锁定的对象经行了“解锁”,导致数据得不到同步的处理,出现不一致的问题

3 使用interrupt方法中断线程

值得注意的是,interrupt()方法并不能真正停止线程,而是在当前线程打了一个停止的标记,可用以下方法停止线程。

public void run() {        while (true) {            if (this.interrupted())                break;            System.out.println("running");        }        System.out.println("退出线程");    }

调用interrupt()方法,this.interrupted()结果为true,退出循环,但会继续执行System.out.println(“退出线程”);然后正常退出线程。可以采用抛异常的方式终止线程,代码如下

public void run() {    try {        while (true) {            if (this.interrupted()) {                throw new InterruptedException();            }            System.out.println("running");        }    } catch (InterruptedException e) {        e.printStackTrace();    }}
0 0
原创粉丝点击