Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Understanding The Life Cycle of a Thread in Java

In this lesson, you will learn.

  • Life Cycle of a Thread

 

1. Life Cycle of A Thread

The life cycle of a thread in Java involves various states in which a thread can exist from its creation until its termination.

Here are the key states in the life cycle of a Java thread.

1. New (Born)

When a new instance of the Thread class is created using either the Thread class or a Runnable object, the thread is in the New state.

At this point, the thread is considered not alive and has not yet started running any code.

Thread t = new Thread(new RunnableTask());  
// The thread t is in the New state.

 

2. Runnable (Ready to run)

When the start() method is called on a Thread object, the thread transitions from the New state to the Runnable state.

In this state, the thread is considered alive and is eligible to run, but it’s not necessarily running immediately.

The thread scheduler of the JVM decides when the thread gets CPU time to execute.

t.start();  
// Now, the Thread 't' is in the Runnable state.

 

3. Running

Once the thread scheduler has selected the thread for execution, it enters the Running state. In this state, the thread’s run() method is actively executing.

The transition between Runnable and Running depends on the JVM thread scheduler and CPU availability.

 

4. Blocked

The thread can be temporarily suspended or blocked from running or state by calling either of the following methods

  1. sleep(long milliseconds): Blocked for a Specified time and returned to the runnable state after a specified time elapsed.
  2. suspend(): Blocked until further order and returned to the runnable state by calling the resume() method.
  3. wait(): Blocked until a certain condition occurs and returned to the runnable state by calling the notify() method.

 

5. Terminated (Dead)

A thread reaches the Terminated state when its run method completes or an uncaught exception causes the thread to abort.

Once a thread is terminated, it cannot be restarted.

public void run() {
    // code runs and finishes
   // The thread will automatically enter the Terminated 
      state upon completion of the run method.
}

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review