Why we call Thread.start() method which in turns calls run method?
Solution 1:
[...] why not we directly call run() method?
The run()
method is just an ordinary method (overridden by you). As with any other ordinary method and calling it directly will cause the current thread to execute run()
.
All magic happens inside start()
. The start()
method will cause the JVM to spawn a new thread and make the newly spawned thread execute run()
.
Solution 2:
If you directly call run() method its body is executed in context of current thread. When you invoke start()
method a new thread is created and run()
method is executed in this new thread.
Solution 3:
Even if programmatically we are not creating any thread, For every application, O.S will create a default thread to execute its code with CPU.
Calling run method directly will make that run method execute in that main thread given by O.S.
But the intention of creating a thread class is to make sure that run method executes in a different thread. Unless thread manager of O.S creates a thread, your run method will not get executed in a separate thread. To request O.S to create the separate thread you have to call start() method which will send a request to O.S to create a thread. Once O.S creates a thread, then O.S will automatically call run method of your thread class in that newly created thread context. And hence your purpose of creating a separate thread and executing your run method in a separate thread will be served.
If you call run method directly, then it is like O.S is not creating any thread for you, and default main thread will execute your run method. No point of creating a separate thread class for that!
Hope I am clear. Let me know if you need more explanation to answer your question.
Note: Though books say JVM creates threads, internally JVM will have to send a request to thread manager driver of O.S layer to create a new thread in its thread pool. That's why I use O.S term more here than JVM.
Solution 4:
Why do we call the thread object's start() method which in turns calls run() method
No it doesn't. start()
calls the operating system, which starts a new thread, which (to simplify greatly) calls the run()
method. Meanwhile the start()
method has already returned to its caller. They are not equivalent.
Solution 5:
Runnable
is just an interface. A class implementing Runnable
is nothing special, it just has a run
method.
Thread#start
is a natively implemented method that creates a separate thread and calls Thread
's run
method, executing the code in the new thread.
Thread
implements Runnable
. The code for run
looks like this:
@Override
public void run() {
if (target != null) {
target.run();
}
}
If the Thread
instance was created by passing a Runnable
to the Thread
's constructor, the Runnable
's run
method is called.
Otherwise, classes extending Thread
have to override the run
method in order for start
to work.
Calling run
on Thread
does NOT create a new thread.