Skip to main content

Threads in Java - start() method and Thread priority (Part 6)

In the previous posts, we have seen that we can start a thread by extending the Thread class or implementing the Runnable interface. In both methods, we override the run() method which is the actual code block where the task assigned to that thread is performed.

Even though we override run() method but we start the thread by calling the start() method. Why do we do that? Wouldn't it be straight-forward if we directly call the run() method? In this post, we will discuss this along with the thread priorities.

What happens when a method is called?

When any method in Java is called, following operations generally take place - 
  • Method arguments are evaluated.
  • A new stack frame is pushed into the call stack.
  • Parameters are initialized.
  • Body is executed.
  • Value is returned and the current stack frame is popped from the call stack.

start() vs run() method

Even if programmatically we are not creating any thread, For every application, OS 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 OS.

To request OS to create the separate thread we have to call start() method which will send a request to OS to create a thread. Once OS creates a thread, then it will automatically call run() method of our thread class in that newly created thread context. And hence our purpose of creating a separate thread and executing your run method in a separate thread will be served.

If we call run() method directly, then it is like OS is not creating any thread for us, and default main thread will execute our run() method. No point of creating a separate thread class for that!

Following code example will demonstrate the above theory - 
This program outputs -
Thread-0: inside run() method
main: inside run() method

We can clearly see that the thread names are different. When we call the start() method, a new thread is spawned while when we call run() method, the code is executed in the current thread only.

Thread Priority

The thread scheduler assigns the processor to a thread based on the latter's priority. Whenever we create a thread, it has a priority - either given by JVM or the programmer itself.

The accepted value of priority for a thread is in range of 1 to 10. There are 3 static variables defined in Thread class for priority.
  • public static int MIN_PRIORITY: This is the minimum priority that a thread can have. Value for this is 1.
  • public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly define it. Value for this is 5.
  • public static int MAX_PRIORITY: This is the maximum priority of a thread. Value for this is 10.
Following code demonstrates the concept - 

Important points

  • Thread with the highest priority will get the chance to execute before other threads.
  • Default priority for main thread is always 5. But it can be changed later.
  • If two threads have the same priority, then we cannot say deterministically which thread will be executed next. It depends on the Thread Scheduler algorithm.
  • If we are using thread priority for scheduling then the underlying platform should provide support for scheduling based on thread priority.

Conclusion

In this post, we discussed the internal implementation of the start() method, the difference between start() and run(), and towards the end we discussed priorities in threads. The code can be found in the commit on my GitHub.

Feel free to befriend me on FacebookTwitter or Linked In or say Hi by email.

Happy Coding 😊 and Happy Learning 😊

Comments

Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
making connectionscachingretrying failed requeststhreadingresponse parsingerror handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object…

Threads in Java - Masterclass (Part 0)

Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -
1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a processor busy can be a tough task e…

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user.

The output of this UI will be like this -
I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started.
Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml fileNavigate to app\src\main\res\values\styles.xmlChange the style value from DarkActionBar to NoActionBar as below<resources><!-- Base application theme. --><stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark&qu…