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.