Thread类isAlive方法

方法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;

 

 

 

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值