您的位置:首页 > 其它

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

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

package cn.itcast_03;

/*
* Thread类的方法:
*         public final String getName() 获取线程对象的名称(放在需要被线程执行的代run()方法里面)
*
*/
public class MyThreadDemo {
public static void main(String[] args) {
// 创建线程对象
// 无参构造
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
my1.start();
my2.start();
}
}


package cn.itcast_03;

public class MyThread extends Thread {

public MyThread() {
}

// 需要被线程执行的代码
@Override
public void run() {
for (int x = 0; x < 100; x++) {
System.out.println(getName() + ":" + x);
}
}
}


我们查看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()方法得到线程对象的名称。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐