2015-05-31 19 views
2

爲什麼我可以訪問getName()方法?我的班級沒有擴展類Thread只是實現了接口RunnablegetName()來自類Thread

public class MyThread implements Runnable { 
    public void run() { 
     System.out.println("MyThread is running"); 
    } 

    public static void main(String[] args){ 
     MyThread thread1 = new MyThread(); 
     Thread thr = new Thread(thread1, "thread"); 
     thr.start(); 
     System.out.println(thr.currentThread().getName()); 
     System.out.println(thr.getName());//Why do I have access to this method? 
    } 
} 

回答

6

您不是在MyThread類的實例上調用getName(),而是在Thread類的實例上調用它。您應該考慮將您的類重命名爲MyRunnable,因爲MyThread看起來像您的類是某種Thread類,而事實並非如此。

0

您執行的每個操作都在一個線程中。如果你正在做一些動作,在啓動程序的主要方法中,它發生在主線程中。

currentThread方法是靜態方法,它提供當前正在執行該線程的線程,並且在執行時,getName()它位於該Thread對象上。