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 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:
- NEW
- RUNNABLE
- TERMINATED
- BLOCKED
- WAITING
- TIMED_WAITING
Below example demonstrates the use of getState() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); System.out.println("Child thread: " + t); System.out.println("State: " + t.getState()); t.start(); } @Override public void run() { System.out.println("State: " + t.getState()); try { for (int i = 1; i <= 3; i++) { System.out.println(t.getName() + ": " + i); Thread.sleep(2000); } } catch (InterruptedException e) { System.out.println(t.getName() + " is interrupted!"); } System.out.println(t.getName() + " is terminated"); } } public class Driver { public static void main(String[] args) { MyThread thread1 = new MyThread("First Thread"); try { System.out.println("Main thread is waiting…"); thread1.t.sleep(1000); System.out.println("State: " + thread1.t.getState()); thread1.t.join(); System.out.println("State: " + thread1.t.getState()); } catch (InterruptedException e) { System.out.println("Main thread is interrupted!"); } System.out.println("Main thread terminated"); } } |
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
Take your time to comment on this article.