Java多线程的Thread.currentThread().getName()和this.getName()的区别

public class currentThread extends Thread{
    public currentThread(){
        System.out.println(" 构 造 方 法 打 印 当 前 线 程 的 名 称 : " + Thread.currentThread().getName());
        System.out.println(" 构 造 方 法 打 印 当 前 线 程 的 名 称 : " + this.getName());
    }
    @Override
    public void run() {

        System.out.println(" 构 造 方 法 打 印 当 前 线 程 的 名 称 : " + Thread.currentThread().getName());
        System.out.println(" 构 造 方 法 打 印 当 前 线 程 的 名 称 : " + this.getName());
    }
}
public class TestcurrentThread {
    public static void main(String[] args) {
        currentThread c=new currentThread();
//此时构造方法已经运行,所以this.getName()返回的不是c c.setName(
"c"); Thread t=new Thread(c); t.setName("t"); t.start(); } }

输出结果:

 构 造 方 法 打 印 当 前 线 程 的 名 称 : main

 构 造 方 法 打 印 当 前 线 程 的 名 称 : Thread-0

 构 造 方 法 打 印 当 前 线 程 的 名 称 : t

 构 造 方 法 打 印 当 前 线 程 的 名 称 : c

 

可以看出this.getName()返回的是方法所在的线程对象名, Thread.currentThread().getName()返回的是正在运行的线程对象名。

posted @ 2021-05-26 17:36  x77  阅读(133)  评论(0)    收藏  举报