您的位置:首页 > 编程语言 > Java开发

Java 终止线程的方法

2012-08-19 16:58 531 查看
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方法只作用于那些因为执行了sleep、wait、join方法而休眠的线程,使他们不再休眠,同时会抛出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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息