如何檢視某個執行緒在 Java 中是否已停止



問題描述

如何檢查一個執行緒是否停止了?

解決方案

以下示例演示瞭如何透過檢查 isAlive() 方法來檢視某個執行緒是否停止了。

public class Main {
   public static void main(String[] argv)throws Exception { 
      Thread thread = new MyThread();
      thread.start();
      
      if (thread.isAlive()) {
         System.out.println("Thread has not finished");
      } else {
         System.out.println("Finished");
      }
      long delayMillis = 5000; 
      thread.join(delayMillis);
      
      if (thread.isAlive()) {
         System.out.println("thread has not finished");
      } else {
         System.out.println("Finished");
      }
      thread.join();
   }
}
class MyThread extends Thread {
   boolean stop = false;
   public void run() {
      while (true) {
         if (stop) {
            return;
         }
      }
   }
}

結果

上述程式碼樣本將產生以下結果。

Thread has not finished
Finished
java_threading.htm
廣告
© . All rights reserved.