一、isAlive() 方法
isAlive() 方法的作用是判断线程是否处于活动状态。什么是活动状态呢?即线程已经启动且尚未终止。线程处于正在运行或准备开始运行的状态,就认为线程是“存活”的。
@Test
public void test() {
IsAliveThread isAliveThread = new IsAliveThread();
System.out.println("[begin]Thread is Alive :[" + isAliveThread.isAlive() + "]");
isAliveThread.start();
System.out.println("[end]Thread is Alive :[" + isAliveThread.isAlive() + "]");
}
public class IsAliveThread extends Thread {
@Override
public void run() {
System.out.println("I am alive Thread");
System.out.println("[running]Thread is Alive :[" + Thread.currentThread().isAlive() + "]");
}
}
运行结果:
[begin]Thread is Alive :[false]
I am alive Thread
[running]Thread is Alive :[true]
[end]Thread is Alive :[false]
or:
[begin]Thread is Alive :[false]
[end]Thread is Alive :[true]
I am alive Thread
[running]Thread is Alive :[true]
结果分析:
[begin]Thread is Alive :[false]:此时线程只是被创建出来,并没有调用 start(),所以此时线程处于非活动状态。
[running]Thread is Alive :[true]:此时线程正在运行,所以线程肯定处于活动状态。
[end]Thread is Alive 则会存在两种结果 [true] or [false]:当结果为false时,表示此时 IsAliveThread已经中止运行,处于非活动状态。当结果为true时,表示此时 IsAliveThread 还未执行完毕,处于活动状态。
更改代码,当我们在主线程加入如下代码 Thread.sleep(1000); 看看结果如何。
@Test
public void test() throws InterruptedException {
IsAliveThread isAliveThread = new IsAliveThread();
System.out.println("[begin]Thread is Alive :[" + isAliveThread.isAlive() + "]");
isAliveThread.start();
Thread.sleep(1000);
System.out.println("[end]Thread is Alive :[" + isAliveThread.isAlive() + "]");
}
public class IsAliveThread extends Thread {
@Override
public void run() {
System.out.println("I am alive Thread");
System.out.println("[running]Thread is Alive :[" + Thread.currentThread().isAlive() + "]");
}
}
执行结果:
[begin]Thread is Alive :[false]
I am alive Thread
[running]Thread is Alive :[true]
[end]Thread is Alive :[false]
结果分析:
主线程中增加了Thread.sleep(1000); 示例的打印结果则为:[end]Thread is Alive :[false],因为 IsAliveThread 对象已经在1秒内执行完毕。