如何使用 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.