Skip to main content

Threads in Java - Lifecycle (Part 2)

A thread at a given point of time can exist only in one of the following sates -
  1. NEW
  2. RUNNABLE
  3. BLOCKED
  4. WAITING
  5. TIMED_WAITING
  6. TERMINATED
These states are defined by an enum named as State defined in the Thread class.
source: javatpoint

Let us discuss these states one by one - 

NEW

When a thread is created it is in the NEW state. This means we have created the instance of the thread but its start() method is not yet called.

RUNNABLE

When we call the start() method, then the thread goes in the RUNNABLE state. In this state, a thread might actually be running or it might be ready to run at any instant of time. The thread is ready to run but waiting for the Thread Scheduler to provide it with the CPU to run.

BLOCKED

In this state, the thread is not eligible to run. It enters this state when it is waiting for a monitor lock and is trying to access a section of code that is locked by some other thread.

WAITING

A thread enters into this state when it is waiting for another thread to perform a specific option. Any thread can enter this state by calling any one of the following three methods:
  1. object.wait()
  2. thread.join() or
  3. LockSupport.park()

TIMED_WAITING

A thread enters into this state when it is waiting for another thread to perform a specific option within a stipulated amount of time. There are five ways to put a thread on TIMED_WAITING state:
  1. thread.sleep(long millis)
  2. wait(int timeout) or wait(int timeout, int nanos)
  3. thread.join(long millis)
  4. LockSupport.parkNanos
  5. LockSupport.parkUntil

TERMINATED

A thread is said to be terminated when it has finished its execution or ended abnormally.

Understanding states of threads using code

Now, we will write some code to understand when does a thread enters into a particular state.
The output of the above code will be -
NEW 
RUNNABLE 
RUNNING 
TIMED_WAITING 
TIMED_WAITING 
WAITING 
TERMINATED 

Let's discuss the code step by step -
  • At line #15, we see that the thread objects are only created not started (start() method is not called), hence the thread is in NEW state
  • When we reach line #22, we have already started the threads but it is not guaranteed whether they have been provided with the resources, hence they are most likely to be in the running state.
  • In ThreadB class we have a method commonResource() which is being shared with tC as well. Since the method is synchronized (which means only one thread can access it at a time) and tB is also using it. This will cause the tB to be in the BLOCKED state.
  • At line #75, we created tC and started it. Then, tC creates tD and starts it. After this, we call tD.join() method, which will make tC to wait until tD is completed.
  • At line # 34, we are starting tE which sleeps for 5 seconds (line # 112) and when we enquire the state of the tE, it will come as TERMINATED.
  • In, the end we start tF with the empty run() method. By the time we enquire the state of this thread, it would have completed its execution and will be in the TERMINATED state.

Conclusion

In this post, we discussed the thread life cycle, it's various states and we also saw these concepts in action by writing code. The code is 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…