currentThread() 可以返回 调用 代码段 的线程信息。
先上一个简单实例
public class ThreadNameTest {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
}
}
输出
main
Process finished with exit code 0
再上一个稍微复杂的实例,先定义一个线程类。
class ThreadAA extends Thread {
public ThreadAA() {
System.out.println("构造方法中");
System.out.println("Thread.currentThread().getName()\t" + Thread.currentThread().getName());
System.out.println("this.currentThread().getName()\t" + this.currentThread().getName());
System.out.println("this.getName()\t" + this.getName());
}
@Override
public void run() {
super.run();
System.out.println("run方法中");
System.out.println("Thread.currentThread().getName()\t" + Thread.currentThread().getName());
System.out.println("this.currentThread().getName()\t" + this.currentThread().getName());
System.out.println("this.getName()\t" + this.getName());
}
}
此时的main方法为
public class ThreadNameTest {
public static void main(String[] args) {
new ThreadAA().start();
//new ThreadAA().run();
}
}
此时的输出为
构造方法中
Thread.currentThread().getName() main
this.currentThread().getName() main
this.getName() Thread-0
run方法中
Thread.currentThread().getName() Thread-0
this.currentThread().getName() Thread-0
this.getName() Thread-0
Process finished with exit code 0
观察输出结果,不难发现:
ThreadAA 类的构造函数 是被 main线程 调用的。
run方法 自动被 名称为 Thread-0 的线程 所调用。
修改 上述 main方法
public class ThreadNameTest {
public static void main(String[] args) {
//new ThreadAA().start();
new ThreadAA().run();
}
}
此时的输出为
构造方法中
Thread.currentThread().getName() main
this.currentThread().getName() main
this.getName() Thread-0
run方法中
Thread.currentThread().getName() main
this.currentThread().getName() main
this.getName() Thread-0
Process finished with exit code 0
修改 上述 main方法
public class ThreadNameTest {
public static void main(String[] args) {
//new ThreadAA().start();
//new ThreadAA().run();
Thread t1 = new Thread(new ThreadAA());
t1.setName("t1");
t1.start();
//t1.run();
}
}
此时的输出为
构造方法中
Thread.currentThread().getName() main
this.currentThread().getName() main
this.getName() Thread-0
run方法中
Thread.currentThread().getName() t1
this.currentThread().getName() t1
this.getName() Thread-0
Process finished with exit code 0
修改 上述 main方法
public class ThreadNameTest {
public static void main(String[] args) {
//new ThreadAA().start();
//new ThreadAA().run();
Thread t1 = new Thread(new ThreadAA());
t1.setName("t1");
//t1.start();
t1.run();
}
}
此时的输出为
构造方法中
Thread.currentThread().getName() main
this.currentThread().getName() main
this.getName() Thread-0
run方法中
Thread.currentThread().getName() main
this.currentThread().getName() main
this.getName() Thread-0
Process finished with exit code 0
从以上实例,不难看出
Thread.currentThread().getName() 和 this.currentThread().getName() 是一回事,返回的是 调用者的名称。
this.getName() 返回的是 当前对象的名称。