Wednesday 23 July 2014

How Thread.start() indirectly calling your run() method?



Signature of the Thread class is "public class Thread implements Runnable", which means that smart JAVA designers gave you a direct implementation of Runnable interface and called it as a Thread class. This Thread class has a reference variable called target (private Runnable target). Thread class contains several constructors, one such constructor can take your new Runnable implementation and point the target reference to your implementation class by using an init method inside the constructor ( private void init(ThreadGroup g, Runnable target, String name,long stackSize)). 

When you call start method on the Thread object, target reference will point to your object, and JVM (Note: call is from JVM not from Thread class) will call run method of the Thread object (this object), run method will simply call target.run() which is nothing but your run method implementation.