While going through the source code of java.lang.Thread
class. Curiously I wanted to see how a run()
method (user defined run()) is called by Thread class. when I am implementing Runnable
interface as below
Thread waiterThread = new Thread(waiter, "waiterThread");
waiterThread.start();
In the above code from Thread
class's constructor init()
method is being called and from there itself they initialized the Runnable
instance as this.target = target
.
from start()
method they are calling a native
method start0()
which may in-turn call run()
method of the Thread
class which causes user defined run()
method to execute.
the following is the run()
method implementation from Thread class:
@Override
public void run() {
if (target != null) {
target.run();
}
}
My question is when we extend java.lang.Thread
class and when we call start()
method as below.
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
target = null
in the above case so is it the native method's (start0()
) responsibility to set target=HelloThread's instance ? and how does a run()
method of mine is called in case when I extend Thread
class?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…