JavaTutorial- 得到线程的名字

得到线程的名字

方法一

public class ExampleCurrentThread extends Thread{

    public ExampleCurrentThread(){
        System.out.println("构造方法的打印:" + Thread.currentThread().getName());
    }

    @Override
    public void run() {
        super.run();
        System.out.println("run方法的打印:" + Thread.currentThread().getName());
    }
}
测试的代码如下:
public class ExampleCurrentThreadTest extends TestCase {

    public void testInit() throws Exception{
        ExampleCurrentThread thread = new ExampleCurrentThread();
    }

    public void testRun() throws Exception {
        ExampleCurrentThread thread = new ExampleCurrentThread();
        thread.start();
        Thread.sleep(1000);

    }

}
结果如下:
构造方法的打印:main       --->testRun()
run方法的打印:Thread-0    --->testRun()
 


构造方法的打印:main       --->testInit() 
总结:

ExampleCurrentThread内部用Thread.currentThread()会显示构造方法的打印是main,是因为Thread.currentThread()返回的是代码段正在被那个线程调用的信息。这里面很显然构造方法是被main线程执行的,而run方法是被我们自己启动的线程执行的,因为没有给他起名字,所以默认是Thread-0。 接下来

方法二

public class ComplexCurrentThread extends Thread{

    public ComplexCurrentThread() {
        System.out.println("begin=========");
        System.out.println("Thread.currentThread().getName=" + Thread.currentThread().getName());

        System.out.println("this.getName()=" + this.getName());
        System.out.println("end===========");
    }

    @Override
    public void run() {
        super.run();
        System.out.println("run begin=======");
        System.out.println("Thread.currentThread().getName=" + Thread.currentThread().getName());
        System.out.println("this.getName()=" + this.getName());
        System.out.println("run end==========");
    }
}

测试的代码如下:
public class ComplexCurrentThreadTest extends TestCase {
	public void testRun() throws Exception {
        ComplexCurrentThread thread = new ComplexCurrentThread();
        thread.setName("byhieg");
        thread.start();

        Thread.sleep(3000);
    }
}
结果如下:
begin=========
Thread.currentThread().getName=main
this.getName()=Thread-0
end===========
run begin=======
Thread.currentThread().getName=Thread-1
this.getName()=byhieg
run end==========
总结
  • 创建对象的时候,构造器还是被main线程所执行,所以Thread.currentThread()得到的就是Main线程的名字,但是this方法指的是调用方法的那个对象,也就是ComplexCurrentThread的线程信息,还没有setName,所以是默认的名字。
  • run方法无论是Thread.currentThread()还是this返回的都是设置了byhieg名字的线程信息。 所以Thread.currentThread指的是具体执行这个代码块的线程信息
  • this能得到的信息是不准确的,因为如果我们在run中执行了this.getName(),但是run方法却是由另一个线程start的,我们是无法通过this.getName得到运行run方法的新城的信息的。而且只有继承了Thread的类才能有getName等方法,这对于Java没有多继承的特性语言来说,是个灾难。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值