Can we Directly Call run() Method Instead of Calling start() Method in Java

What if run() method is called directly on a Java thread rather than calling the start() method is a very frequently asked interview question. This post discusses in detail why you need to call start() method and what exactly happens if you call run() method directly.

Need to call start() method

When you create a thread in Java and call its start() method it is scheduled to run (it is in Runnable state). It is the scheduler of the underlying Operating System that schedules the runnable thread to run (by allotting CPU cycles) and then only JVM calls the run() method of the thread.

So, the run() method is not directly called by the developer but it doesn’t mean you can’t call run() method directly. Let’s see what happens if you call run() method directly in Java.

What happens when run() method is called directly

If you call the run() method directly rather than following the convention of calling the start() method, no new thread will actually be started. The logic you have written in the run() method will be executed with in the context of the current thread, which most probably will be the main thread.

So not calling the thread’s start method and directly calling the run() method will mean a new thread is not spawned and run() method will run as a normal overridden method.

Example Java code

In the example code two threads are created and then directly run() method is called, since start() method is not called so run method will be executed with in the context of the current thread sequentially. You can see in the output there is no concurrent execution as run() method is called sequentially for two threads, also notice the thread name which is the main thread.

Output

Same example when start() method is called rather than directly calling the run() method. You can see in the output that threads are concurrently executing now. Also notice the thread names now, the names are of the created threads now.

Output

That’s all for the topic Can we Directly Call run() Method Instead of Calling start() Method in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. Hello There. I found your blog using msn. This
    is a very well written article. I’ll be sure to bookmark it and return to read more of
    your useful information. Thanks for the post.
    I will definitely return.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.