public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
} }
According to Java Doc
The
Runnable
interface defines a single method,run
, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor.
So, When we execute HelloRunnable, who calls the inside run method?
In the Thread
class, the start
method looks like this:
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
From this code, we can see that the start method is not calling the run()
method.
start0
method, does it callrun
method? I mean, there's no magic, right? Ifrun
gets called, someone must be calling it :-) – Cainozoicrun()
method is not called from anywhere inside thestart()
call. If thread A callst.start()
, you wouldn't wantt.run()
to be called by thread A would you? You'd want it to be called by a different thread. But, thet.start()
call happens in thread A, and everything that is directly or indirectly called byt.start()
happens in thread A. Thet.run()
method gets called from somewhere else. – Unamerican