Threads , Lifecycle Explained With Example

What is Thread ?
Thread is a sequence of code executed independently with other threads of control with in a single executed program. Multi threading enables you to write in a way where multiple activities can proceed concurrently in the same program.

Why Threads?
If the program is break into different parts , then it is easier to write code for the algorithm as separate tasks or threads .Please note that , using thread in the program does not make the program to execute faster . But it sorts of create an illusion .

Life Cycle of a Thread?
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

threadstates

Above-mentioned stages are explained here:

New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

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.

Running
The thread is in running state if the thread scheduler has selected it.

Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

Terminated
A thread is in terminated or dead state when its run() method exits.

Creating a Thread

A thread can be created by two ways :

(1) By extending the thread class
(2) By implementing the runnable interface

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…

By implementing the 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…

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation