isAlive( ) 方法是用來判斷線程是否啟動的方法。它的傳回值是布爾型,啟動為true,沒啟動為false。
下面的代碼說明了isAlive的使用方法:
public class demoisAlive extends Thread{ //建立線程類
public void run(){ //覆寫線程類的run方法
for(int i=1;i<6;i++)
printMsg(); //run方法調用printMsg方法
}
public void printMsg(){ //被調用的msg方法
Thread t = Thread.currentThread(); //msg方法中得到目前線程的引用,并存入線程類型的引用變量t
String name = t.getName(); //使用此引用變量得到目前線程的名字
System.out.println("new thread name " +name); //輸出這個線程的名字
System.out.println("new thread status "+t.isAlive()); //輸出這個線程的狀态
}
public static void main(String[] args){
demoisAlive d = new demoisAlive(); //建立線程類的執行個體
System.out.println(d.isAlive()); //輸出此線程類的執行個體的狀态
d.start(); //啟動線程類的執行個體,啟動線程
System.out.println(d.isAlive()); //再次輸出此線程類的執行個體的狀态
for(int i=1;i<6;i++)
d.printMsg(); //在主方法中直接調用線程類的方法
System.out.println(d.isAlive()); //最後再檢查一下線程類的執行個體的狀态
}
}
可見,在沒有使用start方法啟動線程類之前,線程的狀态是false;啟動了之後,線程的狀态才是true。
兩個線程交替運作,新的線程完全執行完代碼後,再檢測其狀态,結果是false了(看最後一行)。