如何使用 Java 中 Thread 類的 isAlive() 方法?


isAlive() 是 Thread 類的其中一個方法,當執行緒處於活躍狀態(在開始執行緒但未執行完時)時返回 true。

示例

class first implements Runnable {
   public void run() {
      try {
         for(int i=0; i<=20; i+=2) {
            Thread.sleep(600); System.out.println(i);
         }
      } catch(Exception e) {
   }
}

class MyThread {
   public static void main(String args[]) {
      first obj = new first();
      Thread thread = new Thread(obj);
      thread.setPriority(Thread.MAX_PRIORITY);
      thread.start();
      System.out.println(thread.isAlive());
   }
}

輸出

true
0
2
4
6
8
10
12
14
16
18
20

更新時間:2020 年 2 月 20 日

274 次觀看

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.