Life Cycle of Thread Simplified in Java

0
27
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.

Here is the pictorial diagram of Thread life cycle:

life cycle of thread diagram
life cycle of thread diagram

Newborn: When a Thread is just created by the new statement but not yet run. It is in 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 other state will be thrown as Exception.
Thread state change
Thread state change

Runnable: The Thread is already ready to run and is awaiting for the control of processor. The Thread may be in queue and waiting 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 thh queue at the end and again waits for it’s 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’s turn come,we need to use yield() method.

Yield method on thread
Yield method on thread

Running: The Thread has the control  of the processor. It’s 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 it’s control in the following situation:

  1. It has been suspended using suspend() method.A suspended Thread can be revived by using resume() method.This is useful when we want to suspend a Thread for some reason due to to certain reason,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 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 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 execution of its run() method or stopped by another Thread.When it completes it execution of run() method,it is said to be natural death.When we kill a Thread by sending stop() method,this is considered as 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 follow 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 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 un runnable state.

stop():

This method is responsible to stop a Thread immediately.This is often an abrupt way to stop a Thread.This moves the state of the current Thread to Dead state.A Thread will also move to dead state automatically whenit reaches the end of it’s method.

The stop() method may be used when the premature death of a Thread is required.The stop() method of the class Thread works by throwing a ThreadDeath object in the run method of a Thread.

isAlive():

Before start() method,isAlive() method always returns false.However after start() method isAlive() returns true. This is used to check the state of teh thread.

It is possible for isAlive() method to return true before start() returns but not before start() method is called.This can happen because the start() method can return either before the started thread begins to run or after it begins to run.The method that called start() and the new thread are now running concurrently.On a multiprocessor environment,the start() method can even return at the same time the started Thread begins to run.

Thread objects have a parent child relationship.However the first thread created in a java environment does not have a parent thread. After the first Tread object is created,the thread object that controls the thread used to create another thread Object is considered to be the parent of the newly created thread.

This parent child relationship is used to supply some default values when a Thread object is created,but has no further significance once a Thread has been created.

suspend(): It temporary stops a thread and later can start the Thread again.

Resume(): This method is received by a suspended Thread.There is no guarantee that the suspended Thread will run immediately as there may be high priority Thread running already or waiting.However this method will make a suspended Thread runnable.

sleep(int n):This method asks java runtime to put current Thread to sleep for n milliseconds.After n milliseconds the Thread will eligible to run again.

Yield():

The yield() method  causes the runtime to switch the context from the current Thread to next available and runnable Thread.This is one way to ensure that the Threads at lower priority do not get started or ignored. So when a thread has nothing to do further, it can call the yield() method of its Thread object. This method tells the scheduler to run a different thread.

The value of calling yield() method depends heavily on whether the scheduling mechanism of the platform on which the code is running is preemptive or non preemptive.

Preemptive scheduling

A preemptive scheduling mechanism guarantees that no single thread uses more than its fair share of the processor. If a thread runs for that amount of time without yielding control to another thread,the scheduler preempts the thread and causes it to stop running so that another thread can run.

Non preemptive scheduling

A non preemptive scheduling mechanism can not preempt threads.A non preemptive scheduler relies on the individual threads to yield control of the processor frequently,so that it can provide reasonable performance.

A thread explicitly yields control by calling the thread object’s yield() method.More often,however,a thread implicitly yields control when it is forced to wait for something to happen else where.

Calling a Thread objects yield() method during a lengthy computation can be quite valuable on a platform that uses a non preemptive scheduling mechanism as it allows other threads to run. Otherwise, the lengthy computation can prevent other threads from running.

On a platform that uses a preemptive scheduling mechanism,calling yield() does not usually make any noticeable difference in the responsiveness of threads.

Once the yield() method has been called , we can tell when the thread will be scheduled to run again.If we want to prevent thread from being scheduled to run until a specified amount of time has elapsed, we need to use sleep() method.

Interrupting a thread

As I said earlier,sleep(),suspend() and wait() are used to block a Thread.A Thread can be temporarily suspended or blocked from entering into runnable and subsequently running state by using either of the following Thread methods:

  • sleep(int n):  blocked for a specific time n
  • suspend(): blocked until further order.
  • wait(): blocked until certain condition occurs
  • join(): One thread waits for another thread to complete it’s execution
  • interrupt(): responsible for interruption of thread execution.

These methods cause the Thread to go into blocked(or not runnable) state. The Thread will return to runnable state when specified time is elapsed in case of sleep(),the resume() method is invoked in case of suspend() and notify() method is called in case of wait().

These methods(wait(),join()) are designed to throw an InterruptedException. These methods temporarily suspend the execution of a thread.If a Thread is waiting for one of these methods to return and another thread calls interrup() on the waiting thread,the method that is waiting throws an InterruptedException.

The interrupt() method sets an internal flag in a Thread object.Before the interrupt() method is called,the isInterrupted() method of the thread object always returns false. After the interrupted() method is called,isInterrupted() returns true.

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