日期:2014-05-20  浏览次数:20601 次

一个关于方法调用的问题
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方法怎么直接调用呢不用产生的对象调用么   ?*/
    }
}

------解决方案--------------------
Thread.currentThread(),已经获得当前线程对象
Thread.currentThread().getName());调用当前线程对象的方法getName()

System.out.println(getName());
因为class MyThread extends Thread该类继承了Thread
所以里面也有getName()方法
------解决方案--------------------
Thread.currentThread()的返回值就是一个thread对象;

System.out.println(getName());//这句是因为class MyThread extends Thread该类继承了Thread所以里面也有getName()方法

------解决方案--------------------
我也是新手 帮你查了api.第一个问题:Thread.currentThread()返回的是一个Thread引用,就是你说的对象的地址。这就是你要的对象。

currentThread
public static Thread currentThread()
Returns a reference to the currently executing thread object.

Returns:
the currently executing thread.
第二个问题:getName()是类Thread的一个方法,子类继承父类,也就能调用了。

getName()
Returns this thread 's name.
我是新手我的意见仅供你参考。