Thread.currentThread().getName与this.getName()理解

在看Java多线程编程核心技术,对Thread.currentThrad.getName()与this.getName运行结果产生了困惑,看了网上一些博客解释,自己也产生了些许想法。

线程类:


public class MyThread extends Thread{
	
   public MyThread() {
    System.out.println("构造方法");
		System.out.println(Thread.currentThread().getName());
		System.out.println(this.getName());
		
		System.out.println("--------------");
   }
	public  void run() {
				System.out.println("run方法");
				System.out.println(Thread.currentThread().getName());
				System.out.println(this.getName());	
				
		
	}
}

运行结果:

构造方法
main
Thread-0
--------------
run方法
Thread-1
Thread-0

构造方法里的currentThraad表示的当前线程是主线程(main),这个好理解。
Thread-0是Thread类会为自动赋值,源码如下:

public Thread() {
        this(null, null, "Thread-" + nextThreadNum(), 0);
    }
   private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }

本文主要解释this.name()
this关键字的意思是指示当前对象,构造方法里的当前对象当然是MyThread.
而run方法的this,有人可能认为指示的是Thread对象,毕竟run方法是线程调用的,其实不是,仍旧指的是MyThread对象。
不信可以做一个测试:
修改测试类代码:

public class Run {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		MyThread mt1 = new MyThread();
		Thread th1 = new Thread(mt1);
		Thread th2 = new Thread(mt1);
		th1.start();
		th2.start();
	}
}

代码运行结果:

构造方法
main
Thread-0
--------------
run方法
Thread-1
Thread-0
run方法
Thread-2
Thread-0

可以看出,构造方法里的,以及两个线程调用this.getName().得到的结果都是Thread-0.这印证了不管创建多少个线程,毕竟MyThread对象就只有一个,this都是指向的这个对象,this在run方法里,run方法都在MyThread类中,this当然要指示所在类的对象了。

找工作途中,第一篇小文,留作纪念,向大佬们学习!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值