代码如下:
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()
方法返回的是当前正在运行的线程吗?
Thread.currentThread()不是返回当前程序运行的线程,而是返回Thread.currentThread()这句代码执行时所在的线程。
所以看到,新的分线程构造时代码在主线程中执行,而run方法内的代码是分线程中执行的。
看输出很容易理解