เมธอด isAlive() ใช้ตรวจสอบว่า thread ยังมีชีวิต (alive) หรือไม่ Alive หมายถึง thread ที่เริ่มทำงานแล้วแต่ยังไม่ terminated เมื่อเรียก run() thread จะทำงานเป็นระยะเวลาหนึ่งแล้วหยุด
Syntax
final Boolean isAlive()
คืนค่า true หาก thread ที่เรียกยังทำงานอยู่และยังไม่ terminated คืนค่า false ในกรณีอื่น
ตัวอย่าง
public class Demo extends Thread {
public void run() {
System.out.println("sample ");
try {
Thread.sleep(25);
} catch (InterruptedException ie) {
}
System.out.println("only ");
}
public static void main(String[] args) {
Demo my_obj_1 = new Demo();
Demo my_obj_2 = new Demo();
my_obj_1.start();
System.out.println("The first object has been created and started");
my_obj_2.start();
System.out.println("The first object has been created and started");
System.out.println(my_obj_1.isAlive());
System.out.println("The isAlive function on first object has been called");
System.out.println(my_obj_2.isAlive());
System.out.println("The isAlive function on second object has been called");
}
}
ผลลัพธ์
The first object has been created and started sample The first object has been created and started sample true The isAlive function on first object has been called true The isAlive function on second object has been called only only
คลาส Demo extends Thread มี run() พิมพ์ sample sleep 25ms พิมพ์ only ใน main สร้าง 2 อ็อบเจ็กต์ start() ทั้งคู่ เรียก isAlive() ตรวจสอบสถานะ