线程停止
Thread提供了一个stop()方法,但是stop()方法是一个被废弃的方法。为什么stop()方法被废弃而不被使用呢?原因是stop()方法太过于暴力,会强行把执行一半的线程终止。这样会就不会保证线程的资源正确释放,通常是没有给与线程完成资源释放工作的机会,因此会导致程序工作在不确定的状态下
那我们该使用什么来停止线程呢
Thread.interrupt(),我们可以用他来停止线程,他是安全的,可是使用他的时候并不会真的停止了线程,只是会给线程打上了一个记号,至于这个记号有什么用呢我们可以这样来用。
publicclassMythread extendsThread{
publicvoidrun(){
super.run();
for(inti =0;i<50000;i++){
if(this.interrupted()){
System.out.println("停止");
break;
}
}
System.out.println("i="+(i+1));
}
}
publicclassRun{
try{
MyThread thread = newMyThread();
thread.start();
thread.sleep(1000);
thread.interrupt(); //打上标记
}catch(Exception e){
System.out.println("main");
e.printStackTrace();
}
System.out.println("end!")
}
虽然这样就会停止下来 ,可是For后面的语句还是会执行。
异常法 退出线程
publicclassMythread extendsThread{
publicvoidrun(){
super.run();
try{
for(inti =0;i<50000;i++){
if(this.interrupted()){
System.out.println("停止");
thrownewException();
}
}
System.out.println("i="+(i+1));
}catch(Exception e){
System.out.println("抛出异常了");
e.printStackTrace();
}
}
}
解释 如果当我们打上了一个标记我们就可以检测到已经打上的时候就返回个true,进入if里面返回了一个异常 这样就终止了。这样做使的线程可以在我们可控的范围里停止
用什么方法去看什么状态呢
this.interrupted():看看当前线程是否是中断状态,执行后讲状态表示改为false this.isInterrupeted():看看线程对象是否已经是中断状态,但是不清除中断状态标记。