我嘗試使用實現Runnable
接口的類的構造函數。但我很驚訝地發現它從未被稱爲。 run()
方法被調用,但是,構造函數從未被調用過。我寫了一個簡單的示例代碼來顯示這種現象。任何人都可以解釋爲什麼會發生?爲什麼實現Runnable接口的類的構造函數未被調用?
public class MyRunner implements Runnable {
public void MyRunner() {
System.out.print("Hi I am in the constructor of MyRunner");
}
@Override
public void run() {
System.out.println("I am in the Run method of MyRunner");
}
public static void main(String[] args){
System.out.println("The main thread has started");
Thread t = new Thread(new MyRunner());
t.start();
}
}
構造函數沒有返回類型。 – Daniel
DO構造函數有返回類型嗎?它是一種方法。刪除「空白」,你就會知道 –
哎呀!感謝那。那對我來說太天真了。 – arsingh1212