How does thread's run method get invoked??
Do we invoke run method by calling Thread class’s start() method?
The answer is "YES". We know that when we call Thread
class’s start() method it in turns calls our implemented Runnable
run() method.
Then you would wonder, what is the point of stretching this
topic further?
But believe me, what we know is the half-truth.
start() method doesn't call run() method directly. It actually calls the start0() method, which is a native method present in Thread class. Below is the Thread class’s start() method snippet.
}
private native void start0();
So the small doubt that comes to our mind is: why the start0() method is native??
Java doesn’t have the capability to communicate with OS
directly. So, it borrows this capability from other languages (like C and C++) by
declaring a method as native and use the existing implementation from other
languages.
The start0() is the example of the native method in java which communicates directly or indirectly with
OS (to be specific with the thread scheduler) to allocate new thread (As a java
developer, we don’t need to bother about internal implementation and how it
communicates with OS).
At the end with a newly allocated thread, the call comes to JVM(Java Virtual Machine), and from there run() method actually gets called.
Comments
Post a Comment