線程停止
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():看看線程對象是否已經是中斷狀態,但是不清除中斷狀態標記。