Java Thread isAlive() 方法



描述

Java Thread isAlive() 方法测试此线程是否处于活动状态。如果线程已启动且尚未终止,则该线程处于活动状态。

声明

以下是 java.lang.Thread.isAlive() 方法的声明

public final boolean isAlive()

参数

返回值

如果此线程处于活动状态,则此方法返回 true,否则返回 false。

异常

示例:使用 isAlive 检查线程是否处于活动状态

以下示例演示了 Java Thread isAlive() 方法的用法。在这个程序中,我们通过实现 Runnable 接口创建了一个线程类 ThreadDemo。在构造函数中,使用 currentThread() 方法检索当前线程,并使用 isAlive() 方法打印线程的状态。

在 main 方法中,我们创建了一个 ThreadDemo 类的新的线程,并使用 start() 方法启动它。然后使用 join(),我们让线程等待直到死亡。最后,再次使用 isAlive() 方法打印其状态。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   public void run() {
   
      Thread t = Thread.currentThread();
      // tests if this thread is alive
      System.out.println("status = " + t.isAlive());
   }

   public static void main(String args[]) throws Exception {

      Thread t = new Thread(new ThreadDemo());
   
      // this will call run() function
      t.start();
   
      // waits for this thread to die
      t.join();
   
      // tests if this thread is alive
      System.out.println("status = " + t.isAlive());
   }
} 

输出

让我们编译并运行上述程序,这将产生以下结果:

status = true
status = false

示例:使用 isAlive 和给定的延迟检查线程是否处于活动状态

以下示例演示了 Java Thread isAlive() 方法的用法。在这个程序中,我们通过实现 Runnable 接口创建了一个线程类 ThreadDemo。在构造函数中,使用 currentThread() 方法检索当前线程,并使用 isAlive() 方法打印线程的状态。

在 main 方法中,我们创建了一个 ThreadDemo 类的新的线程,并使用 start() 方法启动它。然后使用 join(),我们让线程等待直到死亡。最后,再次使用 isAlive() 方法打印其状态。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   public void run() {
   
      Thread t = Thread.currentThread();
      // tests if this thread is alive
      System.out.println("status = " + t.isAlive());
   }

   public static void main(String args[]) throws Exception {

      Thread t = new Thread(new ThreadDemo());
   
      // this will call run() function
      t.start();
   
      // waits for this thread to die
      t.join(2000);
   
      // tests if this thread is alive
      System.out.println("status = " + t.isAlive());
   }
} 

输出

让我们编译并运行上述程序,这将产生以下结果:

status = true
status = false
java_lang_thread.htm
广告
© . All rights reserved.