Java可以使用Thread
类,isAlive()
方法检查线程是否仍然存活。isAlive()
方法返回一个布尔值,如果线程仍然在运行,则返回true
;如果线程已经死亡(完成执行或未启动过),则返回false。
示例:
public class ThreadAliveExample {
public static void main(String[] args) throws InterruptedException {
// 创建线程
Thread myThread = new Thread(() -> {
try {
// 线程休眠
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 恢复中断状态
}
System.out.println("Thread has finished execution.");
});
// 启动线程
myThread.start();
// 检查线程是否存活
System.out.println("Is thread alive? " + myThread.isAlive());
// 等待一段时间
Thread.sleep(1000);
System.out.println("Is thread still alive after 1 second? " + myThread.isAlive());
// 再等待足够长的时间,确保线程完成执行
Thread.sleep(3000);
System.out.println("Is thread alive after thread has finished? " + myThread.isAlive());
}
}
运行结果:
Is thread alive? true
Is thread still alive after 1 second? true
Thread has finished execution.
Is thread alive after thread has finished? false