Avik Dutta Avik Dutta - 1 month ago 5x
Java Question

Which method does call the run()?

public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
if (stopBeforeStart) {

From this code we can see that the start method is not calling the run() method.

(new Thread(new HelloRunnable())).start();

So when we call the like the line above, who does call the run method inside?


It is stated right in the documentation of start:

the Java Virtual Machine calls the run method of this thread

So, it is the native code in start0 of the JVM that takes care of calling run in the newly created thread. (This is not quite unexpected, as launching a thread is very OS-specific and cannot be implemented in pure Java.)

Just to clarify, here is a short description of the involved methods:

  • start is the high-level function to start a new Thread.
  • start0 is the native method which creates a new Thread from the operating system and is responsible to ensure that run is called.
  • run is the method defined in your Runnable classes. This method is what will be executed in the new thread. A Thread object in Java itself has no idea about the user code it should execute. This is the responsibility of the associated Runnable object.

Thus, when you call Thread.start(), the run method of the Runnable will automatically be called.

Of course, you can always call the run method of a Runnable explicitly:

HelloRunnable hr = new HelloRunnable();

However, this will, of course, not be executed in a separate thread, but block the execution.