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()返回的是正在运行的线程对象名。

浙公网安备 33010602011771号