Java多執行緒學習(1)——停止執行緒
阿新 • • 發佈:2019-01-26
目錄:
1.interrupt方法學習(基礎知識)
2.異常法
3.sleep法
4.return法
5.stop法(不推薦)
1.interrupt方法學習(基礎知識)
呼叫interrupt方法只是對執行緒做了一個標記(停止標記),並沒有停止執行緒的效果,需要結合以下兩種方法:
1)interrupted():測試當前執行緒是否已經中斷,(靜態方法,當前執行緒是指執行該方法的執行緒)
如果呼叫了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
2)isInterrupted():測試執行緒是否已經
ThreadTest thread=new ThreadTest();
thread.start();
thread.interrupt();
System.out.println(thread.isInterrupted());
結果為: true,它不會清除中斷狀態
2.異常法
public class test{
public static void main(String[] args){
ThreadTest thread=new ThreadTest();
thread.start();
thread.interrupt();
}
}
class ThreadTest extends Thread{
public void run(){
try{
for(int i=0;i<100000;i++){
if(this.interrupted()){
throw new InterruptedException();
}
//code
}
//code
}catch(InterruptedException e){
//code
}
}
}
3.sleep法
如果執行緒在sleep()狀態下停止執行緒,會進入catch語句,並且清除狀態值
public class test{
public static void main(String[] args){
ThreadTest thread=new ThreadTest();
thread.start();
thread.interrupt();
}
}
class ThreadTest extends Thread{
public void run(){
try{
for(int i=0;i<100000;i++){
//code
}
Thread.sleep(10000);
}catch(InterruptedException e){
//code
}
}
}
程式碼會執行完for迴圈中的程式碼後,進入到catch語句
4.return法
public class test{
public static void main(String[] args){
ThreadTest thread=new ThreadTest();
thread.start();
thread.interrupt();
}
}
class ThreadTest extends Thread{
public void run(){
for(int i=0;i<100000;i++){
if(this.interrupted()){
return;
}
//code
}
}
}
5.stop法
呼叫stop()方法,會暴力中斷執行緒,該方法已作廢,原因:1)有可能使一些收尾工作得不到完成
2)容易出現數據不一致的問題