java停止线程的方法

来源:互联网 发布:数据处理软件 编辑:程序博客网 时间:2024/05/17 03:19

首先我们先查看API文档,找到Thread这个类,从这个类中我们找到了stop()这个方法。但是,

stop

@Deprecatedpublic final void stop()
已过时。 该方法具有固有的不安全性。用 Thread.stop 来终止线程将释放它已经锁定的所有监视器(作为沿堆栈向上传播的未检查ThreadDeath 异常的一个自然后果)。如果以前受这些监视器保护的任何对象都处于一种不一致的状态,则损坏的对象将对其他线程可见,这有可能导致任意的行为。stop 的许多使用都应由只修改某些变量以指示目标线程应该停止运行的代码来取代。目标线程应定期检查该变量,并且如果该变量指示它要停止运行,则从其运行方法依次返回。如果目标线程等待很长时间(例如基于一个条件变量),则应使用interrupt 方法来中断该等待。

我们知道了stop()这个方法不安全,那怎么来停止线程呢,我想大家都在思考这个问题。我写了2个实例,供大家参考。

No.1——

public class ThreadDemo2{
public static void main(String arges[]){
Dog d=new Dog();
Thread t=new Thread(d);
t.start();
}
}
class Dog implements Runnable{
int times=0;
public void run(){
while(true){
try{
Thread.sleep(1000);
}catch(Exception e){}
times++;
System.out.println("当前是:"+times);
if(times==5){
break;
}
}
}
}

No.2——

public class ThreadDemo3{
public static void main(String arges[]){
Cat c=new Cat();
Thread t1=new Thread(c);
t1.start();
}
}
class Cat implements Runnable{
int times=0;
boolean t=true;
public void run(){
while(t){
try{
Thread.sleep(1000);
}catch(Exception e){}
System.out.println("hello");
times++;
if(times==5){
this.stop();
}
}
}
public void stop(){
t=false;
}
}

原创粉丝点击