得到线程的名字
方法一
public class ExampleCurrentThread extends Thread{
public ExampleCurrentThread(){
System.out.println("构造方法的打印:" + Thread.currentThread().getName());
}
@Override
public void run() {
super.run();
System.out.println("run方法的打印:" + Thread.currentThread().getName());
}
}
测试的代码如下:
public class ExampleCurrentThreadTest extends TestCase {
public void testInit() throws Exception{
ExampleCurrentThread thread = new ExampleCurrentThread();
}
public void testRun() throws Exception {
ExampleCurrentThread thread = new ExampleCurrentThread();
thread.start();
Thread.sleep(1000);
}
}
结果如下:
构造方法的打印:main --->testRun()
run方法的打印:Thread-0 --->testRun()
构造方法的打印:main --->testInit()
总结:
ExampleCurrentThread内部用Thread.currentThread()会显示构造方法的打印是main,是因为Thread.currentThread()返回的是代码段正在被那个线程调用的信息。这里面很显然构造方法是被main线程执行的,而run方法是被我们自己启动的线程执行的,因为没有给他起名字,所以默认是Thread-0。 接下来
方法二
public class ComplexCurrentThread extends Thread{
public ComplexCurrentThread() {
System.out.println("begin=========");
System.out.println("Thread.currentThread().getName=" + Thread.currentThread().getName());
System.out.println("this.getName()=" + this.getName());
System.out.println("end===========");
}
@Override
public void run() {
super.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("run end==========");
}
}
测试的代码如下:
public class ComplexCurrentThreadTest extends TestCase {
public void testRun() throws Exception {
ComplexCurrentThread thread = new ComplexCurrentThread();
thread.setName("byhieg");
thread.start();
Thread.sleep(3000);
}
}
结果如下:
begin=========
Thread.currentThread().getName=main
this.getName()=Thread-0
end===========
run begin=======
Thread.currentThread().getName=Thread-1
this.getName()=byhieg
run end==========
总结
- 创建对象的时候,构造器还是被main线程所执行,所以Thread.currentThread()得到的就是Main线程的名字,但是this方法指的是调用方法的那个对象,也就是ComplexCurrentThread的线程信息,还没有setName,所以是默认的名字。
- run方法无论是Thread.currentThread()还是this返回的都是设置了byhieg名字的线程信息。 所以Thread.currentThread指的是具体执行这个代码块的线程信息
- this能得到的信息是不准确的,因为如果我们在run中执行了this.getName(),但是run方法却是由另一个线程start的,我们是无法通过this.getName得到运行run方法的新城的信息的。而且只有继承了Thread的类才能有getName等方法,这对于Java没有多继承的特性语言来说,是个灾难。