线程终止的方法

1.异常法(使用退出标志,使线程正常退出)

    

public class MyThread extends Thread{
    public void run(){
        super.run();
        try {
            for (int i = 0; i < 5000000; i++) {
                if(this.interrupted()){
                    System.out.println("停止状态");
                    throw new InterruptedException();
                }
                System.out.println("i="+(i+1));
            }
            System.out.println("for 循环下面");
        }catch (InterruptedException e){
            System.out.println("进入catch");
            e.printStackTrace();
        }
    }
}
 
public class Run {
    public static void main(String[] args) {
        try {
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(2000);
            thread.interrupt(); //这个地方相当于打上了中断标志,然后在异常中去处理
        }catch (InterruptedException e){
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end");
    }
}


 

2.使用stop方法强行终止

 

    该方法已经作废,因为会使数据产生不一致性,程序执行就不确定了

    (suspend方法也同样已经被遗弃,因为该方法可能造成同步对象被一直占用,相当于死锁)

3.使用interrupt方法中断线程

    使用interrupt()+return结合

public void run(){
    while(true){
        if(this.interrupted()){
            System.out.println("停止了");
            return;
        }
        System.out.println("timer=" + System.currentTimeMillis());
    }

}
 
public static void main(String[] args) throws InterruptedException {
    MyThread thread = new MyThread();
    thread.start();
    Thread.sleep(2000);
    thread.interrupt();
}

 

 

 

    但是这个方法可能造成代码中出现多个return,造成污染

所以使用异常法来停止线程,在catch块中可以对异常信息进行相关处理,而且异常流能更好、更方便的控制程序的运行流程。不至于像第三种方法中可能出现多个return。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值