安全的终止线程的两种方法

过期的suspend()、resume()、stop()

不建议使用这三个函数来停止线程,以suspend()方法为例,在调用后,线程不会释放已经占有的资源(比如锁),而是占有着资源进入睡眠状态,这样容易引起死锁问题。同样,stop()方法在终结一个线程是不会保证线程的资源正常释放,通常识没有给予线程完成资源释放工作的机会,因此会导致程序可能工作在不确定的状态下。

两种安全终止线程的方法

package test;

import java.util.concurrent.TimeUnit;

public class ShowDownThread {
private static class TargetRunnable implements Runnable{
    private boolean isCancel = false; //自定义一个终止标志位;
    private long  i;
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(!isCancel&&!Thread.currentThread().isInterrupted()) {
            i++;
        }
        System.out.println("Count i="+i);
    }
    
    public void cancel() {
        isCancel =true;
    }
    
}
public static void main(String[] args) throws InterruptedException {
    TargetRunnable  runnable = new TargetRunnable();
    Thread thread = new Thread(runnable,"CounThread");
    thread.start();
    TimeUnit.SECONDS.sleep(1);  //底层是调用的 Thread.sleep(ms, ns);
    thread.interrupt();// Just to set the interrupt flag;
    
    TargetRunnable runnable1 = new TargetRunnable();
    Thread thread1 = new Thread(runnable1,"CountThread1");
    thread1.start();
    TimeUnit.SECONDS.sleep(1);
    runnable1.cancel();
    
    
}
}

运行结果
873621-20180815150306074-108665326.png
两种方式,一是调用interrupt()方法,其实这也是一种中断标志的方式;二是自己在线程中自定义一个标志位;

转载于:https://www.cnblogs.com/LynnMin/p/9481485.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值