Java多线程Thread.currentThread()的疑问

代码如下:

public class ThreadTest extends Thread
{
    public ThreadTest()
    {
        System.out.println("构造方法a:" + Thread.currentThread().getName());
        System.out.println("构造方法b:" + this.getName());
    }

    @Override
    public void run()
    {
        System.out.println("run方法a:" + Thread.currentThread().getName());
        System.out.println("run方法b:" + this.getName());
    }
    
    public static void main(String[] args)
    {
        Thread thread = new ThreadTest();
        thread.setName("thread");
        
        thread.start();
    }
    
}

运行结果:

构造方法a:main
构造方法b:Thread-0
run方法a:thread
run方法b:thread

问题:
1、构造方法中的this.getName()方法的返回值怎么得出来的?
2、run()方法里的this是否指代当前运行的线程?
3、Thread.currentThread()方法返回的是当前正在运行的线程吗?

新手求指点,多谢!!!

阅读 6.2k
4 个回答
新手上路,请多包涵

Thread.currentThread()不是返回当前程序运行的线程,而是返回Thread.currentThread()这句代码执行时所在的线程。

所以看到,新的分线程构造时代码在主线程中执行,而run方法内的代码是分线程中执行的。

看输出很容易理解

1、new一个Thread对象的时候默认的名字就是Thread-n格式的,你可以看看Thread源码。
2、你这就是一个线程对象,this在你这样使用的情况下,是当前的线程了。
3、Thread.currentThread()永远都是返回当前运行的线程。

新手上路,请多包涵

构造方法运行结果可以理解,但是为什么run方法的运行结果不是setName里的testThread而是thread呢?

1.getName()方法是从Thread类继承来的,看看Thread类的getName()方法就知道了:

    /**
     * Returns this thread's name.
     *
     * @return  this thread's name.
     * @see     #setName(String)
     */
    public final String getName() {
        return String.valueOf(name);
    }

2.是
3.是
构造器中,Thread.currentThread()是main线程,run方法中的Thread.currentThread()是当前线程

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题