A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘勇强 中级黑马   /  2013-3-8 22:03  /  1467 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 刘勇强 于 2013-3-9 13:24 编辑

  1. class Test extends Thread
  2. {
  3.         // private String name;
  4.         Test(String name)
  5.         {
  6.                 //this.name = name;//

  7.                 super(name);        
  8.         }
  9.         public void run()
  10.         {        
  11.                 for (int x= 0;x < 60; x++)
  12.                 {
  13.                         System.out.println((Thread.currentThread()==this)+"--test--"+x+"--"+this.getName());
  14.                 }
  15.                
  16.         }
  17. }

  18. class  ThreadTest
  19. {
  20.         public static void main(String[] args)
  21.         {
  22.                 Test t1 = new Test("one--");
  23.                 Test t2 = new Test("two++");
  24.                 t1.start();
  25.                 t2.start();

  26.                 for (int x = 0;x < 60; x++)
  27.                 {
  28.                         System.out.println("--main--" + x);
  29.                 }
  30.                
  31.         }
  32. }
复制代码
用super(name); 运行后可以得到正确的结果,显示线程的名称。


class Test extends Thread
{
private String name;
Test(String name)
{
this.name = name;
}
为什么上面这种情况不行呢? 线程对象初始化时,“one--”参数赋给name

3 个回复

倒序浏览
你好好看看jdk文档,thread类里实现了getName()和setName()方法,而且是被final修饰的,要想修改的话只能调用父类(Thread)的setName()方法来进行修改,再用getName()来获取。像上边用的this.name=name;这句代码,name只是Test类的局部变量,跟线程的名称name没关系!
回复 使用道具 举报
这要从Thread 类的构造函数本身来说了   他的构造函数怎么实现这个命名规则的  你是不知道的   不过他给提高了 setName  和 getName 两种方法来修改和获取名称。
因为父类中构造函数对于线程名的  命名规则你不知道  你也不能单纯的以为 this.name =name  就可以进行修改了  除非你能复写 getName方法 来获取你 的构造函数 进行的命名  

但 getName是final修饰的 你不能复写  所以你要想对线程名进行修改,就两种办法:  super(name)  或者 setName
回复 使用道具 举报
本帖最后由 李辉 于 2013-3-9 05:51 编辑

其实最根本的原因是Thread的name字段是私有的,即使Thread的子类也看不到name字段。证据是下面的java源代码
public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    private char        name[];
    private int         priority;
    private Thread      threadQ;
    private long        eetop;

  这是从JDK里的源代码文件里找到的。
   
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马