Life Cycle of Thread Simplified in Java

0
252
Spread the love
  • 29
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    138
    Shares

Life Cycle of Thread

Each Thread is java goes through different states when it is created and when it is dead. Read about Thread creation here. Also, read Thread Class here. In this post, I will try to cover the different Thread states.
Below are the Thread states:

  • Newborn
  • Runnable
  • Running
  • Blocked
  • Dead

Below are the methods that move Threads from one state to another.

  • start()
  • stop()
  • suspend()
  • resume()
  • sleep()
  • yield()

Out of which sleep(), suspend() and wait() are used to block a Thread.

Every thread begins its life by calling a run() method. run() holds the body of the code that holds the code that needs to be executed. It is public. It does not take any arguments. It does not have a return value too. It is not allowed to throw an exception.

Here is the pictorial diagram of the Thread life cycle:

life cycle of thread diagram
the life cycle of thread diagram

Newborn: When a Thread is just created by the new statement but not yet run. It is in the newborn state. In this case, the local data members are allocated and initialized. The newborn Thread is not scheduled for running. At this stage we can do two things:

  1. Schedule it for running using start() method
  2. kill it by using kill() method.

Once scheduled, it moves to the runnable state. Any other attempts to move to another state will be thrown as an Exception.

Thread state change
Thread state change

Runnable: The Thread is already ready to run and is waiting for the control of the processor. The Thread may be in the queue and waiting for their turn to be executed. If all the Threads have equal priority, then they are given time slots for execution in round-robin fashion. i.e first come first serve basis.

The Thread that relinquishes control joins the queue at the end and again waits for its turn. The process of assigning time to Threads is known as time slicing. However, if we want a Thread to relinquish control to another Thread equal priority before it turns to come, we need to use the yield() method.

Yield method on thread
Yield method on the thread

Running: The Thread has the control of the processor. Its code is currently being executed. The thread will continue in this state until it gets preempted by a higher priority Thread or until it relinquishes control. A running Thread may relinquish its control in the following situation:

  1. It has been suspended using suspend() method. A suspended Thread can be revived by using a resume() method. This is useful when we want to suspend a Thread for some reason due to certain reasons, but we do not want to kill it.
  2. If the Thread has been made to sleep using the sleep(timeout) method. This signifies that the Thread is out of the queue for this timeout period. The Thread will reenter into the runnable state as soon as the timeout period elapsed.
  3. If the Thread has been told to wait until some event occurs. This is done using the wait() method. The Thread can be rescheduled to run again using the notify() method.
interruption in thread execution
interruption in thread execution

Blocked: A Thread is blocked when it is prevented from the Runnable or running state and is waiting for some event in order to reenter the scheduling queue. This happens when the Thread is suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

Dead: The Thread has finished it’s the execution of its run() method or stopped by another Thread. When it completes its execution of a run() method, it is said to be a natural death. When we kill a Thread by sending a stop() method, this is considered a premature death. A Thread can be killed as soon as it is born or while running or in not runnable condition.

in summary, a thread dies when one of the following happens:

  • The run() method called by the Thread returns.
  • An exception is thrown that causes the run() method to be exited.
  • A stop() method of the thread is called.

The methods to change the Thread status:

start():

A newborn state can only start if the start() method is called. Once start() is called a thread proceeds to execute the run() method of its target object.

A newborn Thread with this method enters into runnable state and java runtime creates a system Thread context and starts its execution. This method for a Thread object can be called once only.

When the start() method is called the Thread object becomes associated with a scheduled thread in the underlying environment. The thread is now scheduled to run until it dies unless it is suspended or go to an unrunnable state.

class MyClass implements Runnable{
...
...
public void run()
{
while(true){
//do something
doSomething();
}
}

To use it, we create a Thread object with an instance of MyClass as its target object and invoke its start() method.

MyClass mc=new MyClass("Hello");
Thread mt=new Thread(mc);
mt.start();

This can be achieved by putting these code in MyClass’s constructor

class MyClass implements Runnable{
Thread mt;
MyClass(String str){
mt=new Thread(this);
mt.start();
}

The argument we pass to Thread constructor is this-  the current object instance. mt is the thread reference that is kept inside the instance variable to stop or do some other operation.

The Thread class itself implements the Runnable interface and it has its own run() method which we can override.

class MyClass extends Thread{
....
public void run(){
while(true){
//do something
doSomething();
}
}

If we create a thread in this way, the default or empty constructor of the Thread class makes itself the default target. By default, the thread executes its own run() method when we call start().

The subclass of Thread must override the run() method of the Thread class as Thread class defines an empty run() method.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 29
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    138
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here