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当然要指示所在类的对象了。

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

你可能感兴趣的:(Java并发编程)