isAlive()软件包java.lang.Thread.isAlive()中提供了此方法。
此方法用于查找线程是否处于活动状态,因此我们需要知道在哪种情况下,如果start()方法已被调用且线程尚未死亡(例如,线程仍处于运行状态且未完成其运行),则该线程处于活动状态执行)。
此方法不是静态的,因此我们也无法使用类名访问此方法。
此方法的返回类型为boolean,因此如果线程处于活动状态(即线程仍在运行并且尚未完成其执行),则返回true;否则返回false(线程将不会处于运行状态并完成其执行)。
此方法不会引发异常。
语法:
final boolean isAlive(){
}参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
此方法的返回类型为boolean,如果线程处于活动状态(即,线程已使用start()方法启动但尚未终止或终止),则返回true;否则返回false。
isAlive()方法示例/* We will use Thread class methods so we are importing
the package but it is not mandate because
it is imported by default
*/
import java.lang.Thread;
class IsThreadAlive extends Thread {
public void run() {
try {
//之前停止了几毫秒
// run()方法完成其执行
Thread.sleep(500);
//当前线程的显示状态仍然有效
System.out.println("Is thread alive in run() method " + Thread.currentThread().isAlive());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
//的类的对象
IsThreadAlive alive = new IsThreadAlive();
//之前仍处于活动状态
//调用start()方法
System.out.println("Is thread alive before start() call:" + alive.isAlive());
alive.start();
//之后,线程的显示状态仍然有效
//调用start()方法
System.out.println("Is thread alive after start() call:" + alive.isAlive());
}
}输出结果
E:\Programs>javac IsThreadAlive.java E:\Programs>java IsThreadAlive Is thread alive before start() call:false Is thread alive after start() call:true Is thread alive in run() method true