Java 终止线程


Thread.stop,Thread.suspend,Thread.resume和Runtime.runFinalizersOnExit这些终止线程运行的方法已经被废弃,使用他们都是不安全的。
目前来说,终止线程可以通过以下方法:
1.设置标志位,通过return、break终止线程

/**
* 设置标志位,通过return,break终止线程。
* @author Administrator
*
*/
class TestRunnable implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<100;i++){
System.out.println("线程"+Thread.currentThread().getName()+":"+i);
if(i==20){
// break;
return;
}
}
}
}

2.通过捕获InterruptedException运行时异常,中断当前线程

* 通过捕获InterruptedException运行时异常,中断当前线程:通过在catch语句中throw new RuntimeException();
* break;return;终止线程。
* 对于InterruptedException异常,是通过调用当前线程的Thread.currentThread().interrupt()实现的。并且
* interrupt方法只作用于那些因为执行了sleepwaitjoin方法而休眠的线程,使他们不再休眠,同时会抛出InterruptedException异常。
* @author Administrator
*
*/
class TestRunnable001 implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){

try {
Thread.sleep(1000);
if(i==5)
Thread.currentThread().interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("异常抛出!");
throw new RuntimeException();
// break;
// return;
}
System.out.println("线程:"+i);
}
}
}

3.通过标志位来终止线程

/**
* 通过设置标志位来终止线程。
* @author Administrator
*
*/
class TestRunnable002 implements Runnable{

private boolean finished;

@Override
public void run() {
// TODO Auto-generated method stub
while(true){
doSomeWork();
if(finished){
System.out.println("线程终止");
System.err.println("sssssssssssss");
break;
}
}
}

private void doSomeWork() {
// TODO Auto-generated method stub
System.out.println("doSomeWork");
finished = true;
}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值