方法isAlive() 的功能是判断当前的线程是否处于活动状态;活动状态就是线程已经启动尚未终止,那么这时候线程就是存活的,则返回true,否则则返回false;
《多线程核心技术》书中讲到isAlive() 时提到,线程作为参数给另一线程启动时,this.isAlive() 与Thread.currentThread().isAlive() 返回值不同,这是因为,Thread.currentThread()的引用对象和this引用对象不同,Thread.currendThread()获取的事使用该方法的线程对象,this获取的是当前对象;
代码如下:ThreadDemo类和测试类Test
public class ThreadDemo extends Thread {
public void run () {
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
System.out.println("this.getName()="+this.getName());
System.out.println("this.isAlive()="+this.isAlive());
}
}
public class Test {
public static void main(String[] args) throws ParseException {
ThreadDemo t1 = new ThreadDemo();
Thread t2= new Thread(t1);
//设置线程名
t2.setName("T");
t2.start();
}
}
运行结果:
可以看到,Thread.currentThread() 和 this 调用getName()和isAlive() 结果明显不同;
我们在ThreadDemo类中将他们的对象地址输出:
public class ThreadDemo extends Thread {
public void run () {
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
System.out.println("this.getName()="+this.getName());
System.out.println("this.isAlive()="+this.isAlive());
//将两个方法引用对像打印到控制台
System.out.println("Thread.currentThread()引用对像"+Thread.currentThread().getClass());
System.out.println("this引用对像"+this.getClass());
}
}
输出结果:
为什么他们引用对象不同呢,看下Thread类的源码:
public class Thread implements Runnable {
private Runnable target;
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
//略
this.target = target;
//略
}
public void run() {
if (target != null) {
target.run();
}
}
}
当Thread t2= new Thread(t1);会初始化一个线程t2,将target对象转为t2对象中的私有对象target;
t2.start()会调用run(),此时run()方法判断target对象是否为null,不为null去调用target指向的ThreadDemo,执行ThreadDemo的run()方法;
Thread.currentThread() 获取调用当前方法的线程对象,所以class = thread;
this获取当前对象,但是实际情况是t2线程启动,调用了ThreadDemo对象的run方法(ThreadDemo线程未启动),所以ThreadDemo对象的isAlive()是false;