最近在看《java多线程编程核心技术》这本书,在看到currentThread()方法这节时,遇到了不懂的问题,后来查阅了一些资料,整理如下。
MyThread.java
public class MyThread extends Thread {
public MyThread() {
// TODO Auto-generated constructor stub
System.out.println("MyThread--begin");
System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
System.out.println("this.getName()="+this.getName());
System.out.println("MyThread---end");
}
public void run(){
System.out.println("run---begin");
System.out.println("run.currentThread().getName()="+Thread.currentThread().getName());
System.out.println("this.getName()="+this.getName());
System.out.println("run---end");
}
}
Run.java
public class Run {
public static void main(String[] args){
MyThread thread=new MyThread();
Thread t1=new Thread(thread);
t1.setName("A");
t1.start();
}
}
结果如下:
解释:
首先要明白的一点是Thread t1=new Thread(thread),t1只是调用了thread里面的run方法而已,t1和thread是两个完全不一样的对象,在开始执行
MyThread thread=new MyThread()时会调用MyThread的构造方法。Thread.currentThread.getName()是获取当前现成的名字,构造器当中返回的自然是main,this.getName()获取的是thread对象的名字,因此是Thread-0。t1.setName("A")仅仅是改变了t1的名字,和thread对象没有关系。Thread的源代码如下:
现在把Run改成如下:
public class Run {
public static void main(String[] args){
MyThread thread=new MyThread();
//Thread t1=new Thread(thread);
//t1.setName("A");
//t1.start();
thread.setName("B");
thread.start();
}
}
结果如下:
这里的threa.setName()就是直接修改的本身的线程名字,因此,this.getName()也会变。但是因为在执行构造方法的时候thread线程还没有执行,所以输出this.getName()=Thread-0