JAVA- Life cycle of a thread

A thread can have five different states, during its life time a thread is always in any one of these states and can move from one state to another. Followings are the states of a thread:

  1. Newborn state
  2. Runnable state
  3. Running state
  4. Blocked state
  5. Dead state

1.      Newbornstate: A Newborn state is a state when a thread object is created, and is not yet scheduled for running.

2.      Runnable state: The runnable state means the thread is ready for the execution. And if all the threads have equal priority then they are given time slots on first come first serve basis.

3.      Running state: In this state the processor has given the time to the thread for execution.

4.      Blocked state: If we preventing the thread from entering into runnable/running state then this state called as blocked state.

5.        Dead state: When a thread has completed its execution using run() method it is called the natural death. And when we stopped or moved a thread to dead state by calling stop() method it causes a premature death.

Program:

//CREATING A THREAD USING A THREAD CLASS

class A extends Thread

{

public void run( )

{

for(int i=1;i<=5;i++)

{

System.out.println(“\t From thread A:”+i);

}

System.out.println(“Exit from A”);

}

}

class B extends Thread

{

public void run( )

{

for(int j=1;j<=5;j++)

{

System.out.println(“\t From thread  b: j=”+j);

}

System.out.println(“Exit from B”);

}

}

 

class C extends Thread

{

public void run( )

{

for(int k=1;k<=5;k++)

{

System.out.println(“\t From thread C: k=”+k);

}

System.out.println(“Exit from c”);

}

}

class threadTest

{

public static void main(String args[ ])

{

new A( ).start( );

new B( ).start( );

new C( ).start( );

}

}

Leave a Reply

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