2016-07-28 156 views
0

我有一個簡單的線程測試代碼片段,它的僞代碼就像這樣new Thread(new Runnable(){...implement run method....}){...override run method...}.start();。我的問題是爲什麼此代碼輸出是'線程:線程..',而不是'runnable:線程..'?這裏是完整的代碼,謝謝!爲什麼這段代碼輸出是'thread:Thread ..',而不是'runnable:Thread ..'?

public class ThreadTest { 


public static void main(String[] args) { 
    new Thread(new Runnable(){//1 annonymous class implement Runnable interface 
     @Override 
     public void run() { 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      System.out.println("runnable:" + Thread.currentThread().getName()); 
     } 
    }){ 
     public void run() {//2 annonymous class extends Thread class 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      System.out.println("thread:" + Thread.currentThread().getName()); 
     }; 
    }.start(); 
} 

}

回答

1

默認情況下,Threadrun方法將委託給你在構造函數中提供Runnable

但是,您會覆蓋Thread的(匿名)子類中的run方法來執行其他操作。