Thread java life cycles
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
Java Thread Life Cycle and States
In Java, a Thread is a lightweight process that allows a program to operate more efficiently by running multiple threads in parallel. Internally, JVM creates a Thread and hands it over to the operating system for execution. The operating system then schedules, executes this thread and performs various state transitions between multiple threads.
During state transitions and life cycle, a Thread goes into various states depending on several factors such as thread priority, forcibly suspending a thread or waiting for the output of blocking operations.
1. Thread Life Cycle States
A Java thread can be in any of the following thread states during its life cycle:
- New
- Runnable (or Running)
- Blocked
- Waiting
- Timed Waiting
- Terminated
These are also called life cycle events of a thread. Let’s understand each state in more detail.
As soon as, you create new thread , it’s in NEW state. Thread remains in New state until the program starts the thread using its start() method. At this point, the thread is not alive.
Thread thread = new Thread(); System.out.println(thread.getState()); //NEW
Calling the thread.start() method puts the thread in RUNNABLE state. At this point, execution control is passed to OS thread scheduler to finish its execution. The thread scheduler decide from this point that this thread should be executed (also known as dispatching the thread) or should be put on hold to give chance to other runnable threads. Thread scheduling is platform dependent — the behavior of a multi-threaded program could vary across different Java implementations.
In most operating systems, each thread is given a small amount of processor time—called a quantum or timeslice—with which to perform its task. A task utilizing it’s quantum is said to be in RUNNING state. When its quantum expires, the thread returns to the RUNNABLE state, and the operating system assigns another thread to the processor.
The process that an operating system uses to determine which thread to dispatch is called thread scheduling and is dependent on thread priorities.
Thread thread = new Thread(); thread.start(); System.out.println(thread.getState()); //RUNNABLE
The operating system hide the RUNNABLE and RUNNING states from the Java Virtual Machine (JVM), which sees only the RUNNABLE state.
A RUNNABLE thread transitions to the BLOCKED state when it attempts to perform a task that cannot be completed immediately and it must temporarily wait until that task completes.
For example, when a thread issues an input/output request, the operating system blocks the thread from executing until that I/O request completes—at that point, the blocked thread transitions to the RUNNABLE state, so it can resume execution. A blocked thread cannot use a processor, even if one is available.
Usually program put a thread in WAIT state because something else needs to be done prior to what current thread is doing. A thread can be put in waiting state using
Once the thread wait state is over, its state is changed to RUNNABLE and it is moved back to thread pool.
A RUNNABLE thread can transition to the TIMED WAITING state if it provides an optional wait interval when it’s waiting for another thread to perform a task. You can put a java thread in TIMED WAITING state by calling using following methods:
- thread.sleep(long millis)
- wait(int timeout) or wait(int timeout, int nanos)
- thread.join(long millis)
Such a thread returns to the RUNNABLE state when it is notified by another thread or when the timed interval expires—whichever comes first. Timed waiting threads and waiting threads cannot use a processor, even if one is available.
A thread enters the TERMINATED state (sometimes called the dead state) when it successfully completes its task or otherwise terminated due to any error or even it was forcefully killed.
2. Deadlock and Starvation
Please remember that though JVM and OS thread scheduler do their best yet sometimes threads can cause starvation or deadlock.
A deadlock occurs when a waiting thread (let us call this thread1) cannot proceed because it is waiting (either directly or indirectly) for another thread (let us call this thread2) to proceed. And simultaneously thread2 cannot proceed because it is waiting (either directly or indirectly) for thread1 to proceed.
In this Java concurrency tutorial, we learned about the lifecycle of a Thread in Java, and how the state transitions happen between different states of the Thread.
Thread Life Cycle in Java — Thread States in Java
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Understanding Thread Life Cycle in Java and Thread States are very important when you are working with Threads and programming for multithreaded environment. From our last tutorial, we can create a java thread class by implementing Runnable interface or by extending Thread class, but to start a java thread, we first have to create the Thread object and call it’s start() method to execute run() method as a thread.
Thread Life Cycle in Java
Below diagram shows different states of thread life cycle in java. We can create a thread in java and start it but how the thread states change from Runnable to Running to Blocked depends on the OS implementation of thread scheduler and java doesn’t have full control on that.
New
When we create a new Thread object using new operator, thread state is New Thread. At this point, thread is not alive and it’s a state internal to Java programming.
Runnable
When we call start() function on Thread object, it’s state is changed to Runnable. The control is given to Thread scheduler to finish it’s execution. Whether to run this thread instantly or keep it in runnable thread pool before running, depends on the OS implementation of thread scheduler.
Running
When thread is executing, it’s state is changed to Running. Thread scheduler picks one of the thread from the runnable thread pool and change it’s state to Running. Then CPU starts executing this thread. A thread can change state to Runnable, Dead or Blocked from running state depends on time slicing, thread completion of run() method or waiting for some resources.
Blocked/Waiting
A thread can be waiting for other thread to finish using thread join or it can be waiting for some resources to available. For example producer consumer problem or waiter notifier implementation or IO resources, then it’s state is changed to Waiting. Once the thread wait state is over, it’s state is changed to Runnable and it’s moved back to runnable thread pool.
Dead
Once the thread finished executing, it’s state is changed to Dead and it’s considered to be not alive. Above are the different states of thread. It’s good to know them and how thread changes it’s state. That’s all for thread life cycle in java.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Life Cycle of Thread in Java | Thread State
Life Cycle of Thread in Java is basically state transitions of a thread that starts from its birth and ends on its death.
When an instance of a thread is created and is executed by calling start() method of Thread class, the thread goes into runnable state.
When sleep() or wait() method is called by Thread class, the thread enters into non-runnable state.
From non-runnable state, thread comes back to runnable state and continues execution of statements.
When the thread comes out of run() method, it dies. These state transitions of a thread are called Thread life cycle in Java.
To work with threads in a program, it is important to identify thread state. So. let’s understand how to identify thread states in Java thread life cycle.
Thread States in Java
A thread is a path of execution in a program that enters any one of the following five states during its life cycle. The five states are as follows:
4. Blocked (Non-runnable state)
1. New (Newborn State): When we create a thread object using Thread class, thread is born and is known to be in Newborn state. That is, when a thread is born, it enters into new state but the start() method has not been called yet on the instance.
In other words, Thread object exists but it cannot execute any statement because it is not an execution of thread. Only start() method can be called on a new thread; otherwise, an IllegalThreadStateException will be thrown.
2. Runnable state: Runnable state means a thread is ready for execution. When the start() method is called on a new thread, thread enters into a runnable state.
In runnable state, thread is ready for execution and is waiting for availability of the processor (CPU time). That is, thread has joined queue (line) of threads that are waiting for execution.
If all threads have equal priority, CPU allocates time slots for thread execution on the basis of first-come, first-serve manner. The process of allocating time to threads is known as time slicing. A thread can come into runnable state from running, waiting, or new states.
3. Running state: Running means Processor (CPU) has allocated time slot to thread for its execution. When thread scheduler selects a thread from the runnable state for execution, it goes into running state. Look at the above figure.
In running state, processor gives its time to the thread for execution and executes its run method. This is the state where thread performs its actual functions. A thread can come into running state only from runnable state.
A running thread may give up its control in any one of the following situations and can enter into the blocked state.
a) When sleep() method is invoked on a thread to sleep for specified time period, the thread is out of queue during this time period. The thread again reenters into the runnable state as soon as this time period is elapsed.
b) When a thread is suspended using suspend() method for some time in order to satisfy some conditions. A suspended thread can be revived by using resume() method.
c) When wait() method is called on a thread to wait for some time. The thread in wait state can be run again using notify() or notifyAll() method.
4. Blocked state: A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for some time in order to satisfy some condition.
5. Dead state: A thread dies or moves into dead state automatically when its run() method completes the execution of statements. That is, a thread is terminated or dead when a thread comes out of run() method. A thread can also be dead when the stop() method is called.
During the life cycle of thread in Java, a thread moves from one state to another state in a variety of ways. This is because in multithreading environment, when multiple threads are executing, only one thread can use CPU at a time.
All other threads live in some other states, either waiting for their turn on CPU or waiting for satisfying some conditions. Therefore, a thread is always in any of the five states.
In this tutorial, we have covered life cycle of thread in Java and thread states with helpful diagrams. Hope that you will have understood the basic concept of thread life cycle.
If you get any incorrect in this tutorial, then please inform our team through email. Your email will be precious to us.
Thanks for reading.
Next ⇒ Creating Multiple Threads in Java ⇐ PrevNext ⇒