Thread.currentThread().getName()和this.getName()区别

参考Tracycater的专栏  ,网址:https://www.2cto.com/kf/201701/586777.html

参考:Java多线程编程核心技术(P17-P18)

package ThreadTest;

public class CountOperate extends Thread{
    
    public CountOperate(){
        System.out.println("CountOperate---begin");
        System.out.println("Thread.currentThread().getName()---"+Thread.currentThread().getName());
        System.out.println("this.getName()---"+this.getName());
        System.out.println("this.isAlive()---"+this.isAlive());
        System.out.println("CountOperate--- end");
    }
    
    @Override
    public void run(){
        
        System.out.println("run---begin");
        System.out.println("Thread.currentThread().getName()---"+Thread.currentThread().getName());
        System.out.println("this.getName()---"+this.getName());
        System.out.println("this.isAlive()---"+this.isAlive());
        System.out.println("run--- end");
    }

}
 

java类:

package ThreadTest;

public class CountOperateRun {

    public static void main(String[] args) {
        
        CountOperate c=new CountOperate();
        Thread t1=new Thread(c);
        t1.setName("A");
        t1.start();
        
    }

}
输出:

CountOperate---begin
Thread.currentThread().getName()---main
this.getName()---Thread-0
this.isAlive()---false
CountOperate--- end
run---begin
Thread.currentThread().getName()---A
this.getName()---Thread-0
this.isAlive()---false
run--- end
 

分析:

CountOperate c=new CountOperate();

调用CountOperate构造函数的是main线程,因此此

Thread.currentThread().getName())=main。此时还没有启动CountOperate子线程。

this代表的是CountOperate对象实例,所以:

this.getName=Thread-0

this.isAlive=false

-----------------------------------------------------------------------------------------------

new Thread(c);会将c对象绑定到一个private的target上。

 t1被执行时,即调用t1.run()的的时候,它会调用target.run()方法,即直接调用CountOperate对象

的run方法,也就是说this.get()实际返回的是target.getName().

而Thread.cunrrentThread().getName()实际是t1.getName(); 如没有she设置值此为Thread.currentThread().getName()---Thread-1

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值