Thread Life Cycle

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 8

Thread Life Cycle

Name:- Sarkhot Tawqir


Roll.No:- 39
Subject:- Java Programming
Class:- SYMCA
What is Thread Life Cycle
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
1. New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2. Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3. Running
The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5. Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread
There are two ways to create a thread:
- By extending Thread class
- By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
Java Thread Example by extending Thread class
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
Output:- thread is running...
Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  

Output:- thread is running...

You might also like