Vaibhav singh
Vaibhav singh

Reputation: 11

how does start() method of thread class call run() method of child class when it implements thread class

How does the start() method of Thread class call the run() method of a child class which implements the Thread class?

I know when we implement Runnable we pass the child class object to the Thread class constructor which has parameter of Runnable. But in the other case we call the start() method, and when the JVM doesn't find start() in the child class, it goes to Thread. Now to call run(), or pass it to the JVM, we need child class reference. How does Thread implement it?

That's an interesting thing to know.

Concurrency is achieved by the JVM, but to have it call run() of the child we need its reference or address.

Upvotes: 1

Views: 206

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27115

The start() method of a Thread instance does not call the run() method. What it does is, it creates a new operating system thread, and it makes arrangements for the run() method to be called in that new thread.*

Meanwhile, the t.start() potentially can return before the other thread enters t.run().


* How it makes those "arrangements" can be completely different from one operating system to another, but generally, it involves making a system call and passing a pointer to a native function that the OS will call. The native function most likely will use the Java Invocation API, to get into Java library code that eventually will call t.run().

Upvotes: 3

Thomas Bitonti
Thomas Bitonti

Reputation: 1234

As noted, Thread.start invokes a native method, which in turn invokes Thread.run:

public synchronized void start() {
    startImpl();
}

private native void startImpl(); 

And the code for Thread.run has:

public void run() {
    if (runnable != null) {
        runnable.run();
    }
}

Here, runnable is either null or is the Runnable instance which was provided when the thread was created. The link to the runnable instance is through the reference which was provided to the thread constructor, and which is held as an instance value of the thread object.

The key behavior is provided by the run method, which must either be implemented directly on the thread, or must be implemented on the runnable object which was provided to the thread constructor.

Upvotes: 2

Related Questions