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.

      

    public synchronized void start() {
       if (threadStatus != 0)
          throw new IllegalThreadStateException();
       group.add(this);
       boolean started = false;
       try {
          start0();
          started = true;
       } finally {
          try {
             if (!started) {
                group.threadStartFailed(this);
             }
          } catch (Throwable ignore) {
       
          }
       }

    }

    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.


Conclusion 

start() method is just a trigger point to execute the run() method. But it doesn't call the run() method directly. A lot of things involved before the run() method actually gets executed. 

OK, before signing off, I am leaving you with the question!!

Can thread's run() method throw checked exception using throws keyword?

Click here to know the answer.

See you in my next post. Till then keep reading!!

Comments

Popular posts from this blog

Can we define explicit constructor for an anonymous inner class?

Why we can not throw exception from Thread’s run method?