判断线程是否存活
- 方法isAlive()的作用是测试线程是否处于活动状态。所谓活动状态,就是线程已经启动但是没有终止。即该线程start之后,被认为是存活的。
测试的代码如下:
public class AliveThread extends Thread{
@Override
public void run() {
super.run();
System.out.println("run方法中是否存活" + " " + Thread.currentThread().isAlive());
}
}
public class AliveThreadTest extends TestCase {
public void testRun() throws Exception {
AliveThread thread = new AliveThread();
System.out.println("begin == " + thread.isAlive());
thread.start();
Thread.sleep(1000);
System.out.println("end ==" + thread.isAlive());
Thread.sleep(3000);
}
}
结果
begin == false
sleep ==true
run方法中是否存活 true
end ==false
总结
- start之前,该线程被认为是没有存活
- run的时候,是存活的
- run方法执行完,又被认为是不存活