top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Life cycle of a thread in Java

+1 vote
415 views

New State

A thread can exist in several states, such as new, runnable, blocked, waiting and terminated, according to its various phases in a program.

When a thread is newly created, it is a new Thread and is not alive.

In this state, it is an empty Thread object with no system resources allocated. So the thread is left as a “new thread” state till the start() method is invoked on it. When a thread is in this state, you can only start the thread or stop it. Calling any method before starting a thread raises an IllegalThreadStateException.

Code snippet

Thread th1Obj=new Thread();

An instance of Thread class is created.

Runnable State

A new thread can be in a runnable state when the start() method is invoked on it. A thread in this state is alive. A thread can enter this state from running or blocked state.

Threads are prioritised because in a single processor system all runnable threads can not be executed at a time. In the runnable state, a thread is eligible to run, but may not be running as it depends on the priority of the thread. The runnable thread, when it becomes on the priority of the thread. The runnable thread, when it becomes eligible for running, executes the instructions in its run() method.

Code Snippet

MyThreadClass myThread = new MyThreadClass();

myThread.start();

An instance of thread is created and is in a runnable state.

Blocked State

Blocked State is one of the states in which a thread:

  • Is alive but currently not eligible to run as it is blocked for some other operation
  • Is not runnable but can go back to the runnable state after getting the monitor or lock.

A thread in the blocked state waits to operate on the resource or object which at the same time is being processed by another thread. A running thread goes to blocked state when sleep(), wait() or suspend() method is invoked on it.

Waiting State

A thread is in this state when it is waiting for another thread to release resources for it. When two or more threads run concurrently and only one thread takes hold of the resources all the time, other threads ultimately wait for this thread to release the resource for them. In this state, a thread is alive but not running.

A call to the wait() method puts a thread in this state. Invoking the notify() or notifyAll() method brings the thread from the waiting state to the runnable state.

Terminated State

A thread, after executing its run() method dies and is said to be in a terminated state. This is the way a thread can be stopped naturally. Once a thread is terminated, it can not be brought back to runnable state. Methods such as stop() and destroy() can force a thread to be terminated.

For more go through the below tutorial:

posted Jul 5, 2017 by Robin Rj

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...