调用Thread类的方法:public final String getName() 为什么得到的线程对象的名称默认是:Thread-0、Thread-1、Thread-2、...呢?

调用Thread类的方法:public final String getName()
为什么得到的线程对象的名称默认是:Thread-0、Thread-1、Thread-2、...呢?

 1 package cn.itcast_03;
 2 
 3 /*
 4  * Thread类的方法:
 5  *         public final String getName() 获取线程对象的名称(放在需要被线程执行的代run()方法里面)
 6  *         
 7  */
 8 public class MyThreadDemo {
 9     public static void main(String[] args) {
10         // 创建线程对象
11         // 无参构造
12         MyThread my1 = new MyThread();
13         MyThread my2 = new MyThread();
14         my1.start();
15         my2.start();
16     }
17 }
 1 package cn.itcast_03;
 2 
 3 public class MyThread extends Thread {
 4 
 5     public MyThread() {
 6     }
 7 
 8     // 需要被线程执行的代码
 9     @Override
10     public void run() {
11         for (int x = 0; x < 100; x++) {
12             System.out.println(getName() + ":" + x);
13         }
14     }
15 }
我们查看getName()方法的底层源码可知
(
): class Thread { private char name[]; public Thread() { init(null, null, "Thread-" + nextThreadNum(), 0); } private void init(ThreadGroup g, Runnable target, String name, long stackSize) { init(g, target, name, stackSize, null); } private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc) { //大部分代码被省略了 ... // 将传进来的name(name为字符串)转化为字符数组 this.name = name.toCharArray(); // this.name 指的是 private char name[]; // name.toCharArray(); 这句中的name是传递进来的name,是由"Thread-" + nextThreadNum()得到的name,nextThreadNum()方法第一次返回的是0,第二次返回的是1,... ... } private static int threadInitNumber; // 0, 1, 2 private static synchronized int nextThreadNum() { return threadInitNumber++; // 0, 1 注意:是后++  nextThreadNum()方法第一次返回的是0,第二次返回的是1,...   } public final String getName() { return String.valueOf(name); // String类的方法:把字符数组转为字符串 } } class MyThread extends Thread { public MyThread() { super(); } }

由以上可知,由
MyThread my1 = new MyThread();
第一次调用无参构造的时候,就会去父类thread 调用位无参构造,而父类的无参构造是一系列的init() 方法,最终得到 Thread-0,启动线程后,再通过Thread类的getName()方法得到线程对象的名称。
同理,
MyThread my2 = new MyThread();
第二次调用无参构造的时候,就会去父类thread 调用位无参构造,而父类的无参构造是一系列的init() 方法,最终得到 Thread-1,启动线程后,再通过Thread类的getName()方法得到线程对象的名称。
原文地址:https://www.cnblogs.com/chenmingjun/p/8711964.html