线程-终止线程执行

1.强制终止

stop()方法
缺点:强制终止会丢数据
不建议使用

public  class myfile{
   
    @SuppressWarnings("deprecation")
	public static void main(String[] args)  {
    	Thread t=new Thread(new myrunnable());
    	t.setName("ttt");
    	t.start();
    	try{
    		Thread.sleep(1000*5);
    	}catch(InterruptedException e){
    		e.printStackTrace();
    	}
    	//5秒后终止线程
    	t.stop();//(已过时,强制终止会丢数据)
    }
}
class myrunnable implements Runnable{
    //run()方法当中的异常不能throws,只能try catch
	//因为run()方法在父类没有抛出任何异常,子类不能比父类抛出更多的异常
	@Override
	public void run() {
		for(int i=0;i<10;i++)
			System.out.println(Thread.currentThread().getName()+"-->"+i);
		try{
			Thread.sleep(1000*1);
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	
}

不过,我的代码好像没有成功
ttt–>0
ttt–>1
ttt–>2
ttt–>3
ttt–>4
ttt–>5
ttt–>6
ttt–>7
ttt–>8
ttt–>9
但是确实有这个方法可以强制终止线程的执行

2.怎么合理终止线程执行

利用boolean设置标记,为true时执行代码,否则终止

public  class a1{
   
	public static void main(String[] args)  {
    	Thread t=new Thread(new myrunnable());
    	t.setName("ttt");
    	t.start();
    	try{
    		Thread.sleep(1000*5);
    	}catch(InterruptedException e){
    		e.printStackTrace();
    	}
    	//5秒后终止线程
    	//将标记设为false
    	t.run0=false;
    }
}
class myrunnable implements Runnable{
    //run()方法当中的异常不能throws,只能try catch
	//因为run()方法在父类没有抛出任何异常,子类不能比父类抛出更多的异常
	
	
	boolean run0=true;
	@Override
	public void run() {
		for(int i=0;i<10;i++){
			if(run0){
				System.out.println(Thread.currentThread().getName()+"-->"+i);
				try{
					Thread.sleep(1000*1);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			else
				//终止线程
				return;
			
		}
			
			
	}
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值