Ok , I know the two standard ways to create a new thread and run it in Java :
-
Implement
Runnablein a class, definerun()method, and pass an instance of the class to a newThread. When thestart()method on the thread instance is called, the run method of the class instance will be invoked. -
Let the class derive from
Thread, so it can to override the methodrun()and then when a new instance’sstart()method is called, the call is routed to overridden method.
In both methods, basically a new Thread object is created and its start method invoked. However, while in the second method, the mechanism of the call being routed to the user defined run() method is very clear, (it’s a simple runtime polymorphism in play), I don’t understand how the call to start() method on the Thread object gets routed to run() method of the class implementing Runnable interface. Does the Thread class have an private field of Type Runnable which it checks first, and if it is set then invokes the run method if it set to an object? that would be a strange mechanism IMO.
How does the call to start() on a thread get routed to the run method of the Runnable interface implemented by the class whose object is passed as a parameter when constructing the thread?
The
Threadkeeps a reference to theRunnableinstance, and calls it in the base implementation ofrun.You can see this in the source: