Java多執行緒學習(1) 停止執行緒

2021-07-28 21:09:03 字數 1394 閱讀 2834

呼叫interrupt方法只是對執行緒做了乙個標記(停止標記),並沒有停止執行緒的效果,需要結合以下兩種方法:

如果呼叫了interrupt()方法,interrupted()返回true,看乙個例子:

threadtest thread=new threadtest();

thread.start();

thread.interrupt();

system.out.println(thread.interrupted());

結果是false,因為interrupted()測試當前執行緒,而

system.out.println(thread.interrupted());
這行**執行的當前執行緒不是thread,該執行緒沒有呼叫interrupt()方法,也就沒有停止標記,所以返回false

再看: thread.currentthread().interrupt();

system.out.println(thread.interrupted());

system.out.println(thread.interrupted());

結果為: true false

原因是:呼叫該方法後,執行緒的中斷狀態由該方法清除,也就是說該方法的判斷依據是有沒有做標記,而呼叫過後會把這個標記清楚,導致第三行的輸出沒有標記了,也就false

threadtest thread=new threadtest();

thread.start();

thread.interrupt();

system.out.println(thread.isinterrupted());

結果為: true,它不會清除中斷狀態

public class test

}class threadtest extends thread

//code

}//code

}catch(interruptedexception e)}}

如果執行緒在sleep()狀態下停止執行緒,會進入catch語句,並且清除狀態值

public class test

}class threadtest extends thread

thread.sleep(10000);

}catch(interruptedexception e)}}

**會執行完for迴圈中的**後,進入到catch語句

public class test

}class threadtest extends thread

//code}}

} 呼叫stop()方法,會暴力中斷執行緒,該方法已作廢,原因:

1)有可能使一些收尾工作得不到完成

2)容易出現資料不一致的問題

Java多執行緒3 停止執行緒

關於執行緒的停止,主要有兩種,一種是自然停止,即執行緒體正常執行完畢。還有一種則是外部干涉,我們主要講的是外部干涉。其實也比較簡單 外部干涉 1 執行緒類中定義執行緒體使用的標識,如boolean型 2 執行緒體中使用該標識 3 提供對外的方法改變該標識 4 外部根據條件呼叫該標識 我們還是用例子來...

多執行緒 執行緒的停止

thread類中stop方法停止執行緒存在安全隱患,怎麼讓乙個執行緒停止執行呢?執行緒的執行一般都是迴圈控制體,通過改變run方法 迴圈控制條件,即可讓執行緒停止。class threadstopdemo system.out.println thread.currentthread getname...

多執行緒11 停止執行緒

1 new thread t new thread 執行緒物件一旦建立就進入到新生狀態 2 當呼叫start 方法,執行緒立即進入就緒狀態,但不意味著立即排程執行 3 排程,進入執行狀態,執行緒才真正執行執行緒體的 塊 4 dead,執行緒中斷或者結束,一旦進入死亡狀態,就不能再次啟動 5 阻塞狀態...