I tried using the constructor of a class which implements Runnable
Interface. But I was surprised to see it was never called. The run()
method was called, however, the constructor was never called. I have written a simple sample code to show the phenomenon. Can anyone explain why this is happening?
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();
}
}
Change public void MyRunner()
to public MyRunner()
(no return type). public void MyRunner()
is not a constructor, it's a method. Constructor declarations don't have a return type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With