问个关于方法调用的问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 04:36:14
class MultiThread
{
public static void main(String[] args)
{
MyThread mt=new MyThread();
mt.setDaemon(true);
mt.start();
int index=0;
while(true)
{
if(index++==1000)
break;
System.out.println("main:"+Thread.currentThread().getName());
}//这句上边的getName方法怎么直接调用呢不用产生的对象调用么 ?
}
}
class MyThread extends Thread
{
public void run()
{
while(true)
System.out.println(getName());/*还有这句的getName方法怎么直接调用呢不用产生的对象调用么 ?*/
}
}

对于第一个问题,及System.out.println("main:"+Thread.currentThread().getName());
Thread.currentThread()这个方法返回的是当前线程对象,然后在后面跟方法就不难理解了,当前线程对象.getName();
对于第二个问题,前面没有对象名的原因是,它省略了this关键字,this表示的是当前类的实例化对象.当前类是MyThread,所以this表示的就是MyThread类的对象.
System.out.println(getName());这句话的完整的写法是:
System.out.println(this.getName());