Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

February 12, 2016 Categories: Multithreading. No Comments on Thread States

In this article we will learn about different thread states along with an example program that demonstrates thread life cycle.

 

Life cycle of a thread refers to all the actions or activities done by a thread from its creation to termination. A thread can be in any one of the following five states during its life cycle:

  • New: A thread is created but didn’t begin its execution.
  • Runnable: A thread that either is executing at present or that will execute when it gets the access to CPU.
  • Terminated: A thread that has completed its execution.
  • Waiting: A thread that is suspended because it is waiting for some action to occur. For example, it is waiting because of a call to non-timeout version of wait() method or join() method or sleep() method.
  • Blocked: A thread that has suspended execution because it is waiting to acquire a lock or waiting for some I/O event to occur.

 

The life cycle of a thread is illustrated in the following diagram:

thread-states

 

The state of a thread can be retrieved using the getState() method of the Thread class. The syntax of this method is as follows:

Thread.State getState()

 

The getState() method returns one of the values in State enumeration. The constants in State enumerations are:

  1. NEW
  2. RUNNABLE
  3. TERMINATED
  4. BLOCKED
  5. WAITING
  6. TIMED_WAITING

 

Below example demonstrates the use of getState() method:

 

Output for the above program is:

Child thread: Thread[First Thread,5,main]
State: NEW
Main thread is waiting…
State: RUNNABLE
First Thread: 1
State: TIMED_WAITING
First Thread: 2
First Thread: 3
First Thread is terminated
State: TERMINATED
Main thread terminated

 

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

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

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me