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

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
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值