运行中的线程如何停止?

停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用Thread.stop()方法,但最好不要用它。虽然它确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且是已被废弃的方法。在java中有以下3种方法可以终止正在运行的线程:

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

2、使用stop方法强行终止,但是不推荐这个方法,因为stop和suspend及resume一样都是过期作废的方法。

3、使用interrupt方法中断线程

前面的两个不讲,stop可以中断线程,不推荐使用,在讲解interrupt方法中断线程之前,首先介绍以下两个方法

1、this.interrupted(): 测试当前线程是否已经中断;

2、this.isInterrupted(): 测试线程是否已经中断;

什么意思???不懂,举个例子

public class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        for (int i=0;i<500000;i++){
            System.out.println("i="+i);
        }
    }
}
public class Test {
    public static void main(String[] args) {
        MyThread thread=new MyThread();
        thread.start();
        try {
            Thread.sleep(100);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行一下?

 瓦特?没停,这是什么情况?其实interrupt方法只是在当前线程打一个停止的标志,验证一下,既然有了停止标志,是不是意味着我可以通过interrupted方法看一下他是否停止?改造一下,

public class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        System.out.println("线程开始");
        for (int i=0;i<500000;i++){
            if(this.isInterrupted()){
                System.out.println("当前线程停止,循环退出");
                break;
            }
            System.out.println("i="+i);
        }
        System.out.println("看看这个东西会不会打印出来?");
    }
}

运行看一下结果?

挺好的,循环退出了,线程停止了吗?其实并没有,注意最后的东西打印出来了,那怎么样才能算是停止线程了呢?我是不是可以在这里抛出个异常?然后再对异常进行处理?也可以才有return,不过还是建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止事件得以传播。改造一下

public class MyThread extends Thread{
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("线程开始");
            for (int i=0;i<500000;i++){
                if(this.isInterrupted()){
                    System.out.println("当前线程停止,循环退出");
                    throw new InterruptedException();
                }
                System.out.println("i="+i);
            }
            System.out.println("看看这个东西会不会打印出来?");
        }catch (InterruptedException e){
            System.out.println("进入catch");
            e.printStackTrace();
        }

    }
}

看一下结果

 问题解决

参考文档:https://mp.weixin.qq.com/s/isb8KxDdwmu76RWnzXtcBA

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值