| 本帖最后由 曹睿翔 于 2013-5-5 20:33 编辑 
 Thread是线程对象,Runnable主宿主对象。
 
 
        测试以下代码,在以下代码中,给Thread类的构造方法传递了一个Runnable实例,同时也实现了Thread的run方法,那么Thread.start()具体会执行哪一个Run方法呢?        结果为运行Thread的run方法。     复制代码 public static void main(String[] args) throws Exception {
       new Thread(new Runnable() {//给Thread的构造方法传递一个Runnable接口
           public void run() {
              while(true){
                  try {
                     Thread.sleep(1000);
                  } catch (InterruptedException e) {
                     e.printStackTrace();
                  }
                  System.err.println("Runnable的RUN方法:"+Thread.currentThread().getName());
              }
           }
       }){
           public void run() {//同时实现Thread的run方法,这段代码会运行
              while(true){
                  try {
                     Thread.sleep(1000);
                  } catch(InterruptedException e) {
                     e.printStackTrace();
                  }
                  System.err.println("线程的RUN方法:"+Thread.currentThread().getName());
              }
           };
       }.start();
    }
为什么会运行Thread类中的run方法呢?查看Thread类源代码的run方法如下: public void run() {     if (target != null) {         target.run();     } } 而target就是Runnable类的对象。可见,如果子类不覆盖run方法,且存在target的情况下,即会运行target的run方法。所以,更准确的说,Runnable不是一个线程,而是一个线程执行的宿主对象。 
 欢迎大家讨论!!
 
 
 
 
 |