如果线程已启动但尚未死亡,则该线程处于活动状态或正在运行。要检查线程是否存在,请使用Thread类的isAlive()方法。如果该线程处于活动状态,它将返回true,否则返回false。
package org.nhooo.example.lang; public class ThreadAliveDemo implements Runnable { public void run() { System.out.println("Running [" + Thread.currentThread().getName() + "]."); } public static void main(String[] args) { Thread t1 = new Thread(new ThreadAliveDemo(), "FirstThread"); Thread t2 = new Thread(new ThreadAliveDemo(), "SecondThread"); // 开始t1 t1.start(); // 检查第一个线程是否处于活动状态。 if (t1.isAlive()) { System.out.format("%s is alive.%n", t1.getName()); } else { System.out.format("%s is not alive.%n", t1.getName()); } // 检查第二个线程是否仍然存在。 // 应该返回false,因为尚未启动t2。 if (t2.isAlive()) { System.out.format("%s is alive.%n", t2.getName()); } else { System.out.format("%s is not alive.%n", t2.getName()); } } }