0% found this document useful (0 votes)
20 views6 pages

Java Thread Lifecycle and States

The document outlines the lifecycle and states of a thread in Java, which include New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated. It explains how threads transition between these states based on their execution and scheduling by the thread scheduler. Additionally, it differentiates between multi-threading and multi-tasking, highlighting their characteristics and examples.

Uploaded by

priyankavelu0403
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views6 pages

Java Thread Lifecycle and States

The document outlines the lifecycle and states of a thread in Java, which include New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated. It explains how threads transition between these states based on their execution and scheduling by the thread scheduler. Additionally, it differentiates between multi-threading and multi-tasking, highlighting their characteristics and examples.

Uploaded by

priyankavelu0403
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lifecycle and States of a Thread in Java

A thread in Java at any point of time exists in any one of the following states. A thread
lies only in one of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
The diagram shown below represent various states of a thread at any instant of time.

Life Cycle of a thread


1. New Thread: When a new thread is created, it is in the new state. The thread has
not yet started to run when thread is in this state. When a thread lies in the new
state, it’s code is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to runnable state. In this
state, a thread might actually be running or it might be ready run at any instant of
time. It is the responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual
thread. Each and every thread runs for a short while and then pauses and
relinquishes the CPU to another thread, so that other threads can get a chance to
run. When this happens, all such threads that are ready to run, waiting for the CPU
and the currently running thread lies in runnable state.
3. Blocked/Waiting state:When a thread is temporarily inactive, then it’s in one of
the following states:
● Blocked
● Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked
state. It’s the responsibility of the thread scheduler to reactivate and schedule a
blocked/waiting thread. A thread in this state cannot continue its execution any
further until it is moved to runnable state. Any thread in these states does not
consume any CPU cycle.
A thread is in the blocked state when it tries to access a protected section of code
that is currently locked by some other thread. When the protected section is
unlocked, the schedule picks one of the thread which is blocked for that section
and moves it to the runnable state. Whereas, a thread is in the waiting state when
it waits for another thread on a condition. When this condition is fulfilled, the
scheduler is notified and the waiting thread is moved to runnable state.
If a currently running thread is moved to blocked/waiting state, another thread in
the runnable state is scheduled by the thread scheduler to run. It is the
responsibility of thread scheduler to determine which thread to run.
4. Timed Waiting: A thread lies in timed waiting state when it calls a method with a
time out parameter. A thread lies in this state until the timeout is completed or until
a notification is received. For example, when a thread calls sleep or a conditional
wait, it is moved to a timed waiting state.
5. Terminated State: A thread terminates because of either of the following reasons:
● Because it exists normally. This happens when the code of thread has
entirely executed by the program.
● Because there occurred some unusual erroneous event, like segmentation
fault or an unhandled exception.
A thread that lies in a terminated state does no longer consumes any cycles of
CPU.
Implementing Thread States in Java
In Java, to get the current state of the thread, use [Link]() method to get the
current state of the thread. Java provides [Link] class that defines the
ENUM constants for the state of a thread, as summary of which is given below:
1. Constant type: New
Declaration: public static final [Link] NEW
Description: Thread state for a thread which has not yet started.
2. Constant type: Runnable
Declaration: public static final [Link] RUNNABLE
Description: Thread state for a runnable thread. A thread in the runnable state is
executing in the Java virtual machine but it may be waiting for other resources from
the operating system such as processor.
3. Constant type: Blocked
Declaration: public static final [Link] BLOCKED
Description: Thread state for a thread blocked waiting for a monitor lock. A thread
in the blocked state is waiting for a monitor lock to enter a synchronized
block/method or reenter a synchronized block/method after calling [Link]().
4. Constant type: Waiting
Declaration: public static final [Link] WAITING
Description: Thread state for a waiting thread. Thread state for a waiting thread. A
thread is in the waiting state due to calling one of the following methods:
1.
● [Link] with no timeout
● [Link] with no timeout
● [Link]
A thread in the waiting state is waiting for another thread to perform a particular
action.
2. Constant type: Timed Waiting
Declaration: public static final [Link] TIMED_WAITING
Description: Thread state for a waiting thread with a specified waiting time. A
thread is in the timed waiting state due to calling one of the following methods with
a specified positive waiting time:
● [Link]
● [Link] with timeout
● [Link] with timeout
● [Link]
● [Link]
3. Constant type: Terminated
Declaration: public static final [Link] TERMINATED
Description: Thread state for a terminated thread. The thread has completed
execution.

// Java program to demonstrate thread states


class thread implements Runnable
{
public void run()
{
// moving thread2 to timed waiting state
try
{
[Link](1500);
}
catch (InterruptedException e)
{
[Link]();
}

[Link]("State of thread1 while it called join() method on thread2 -"+


[Link]());
try
{
[Link](200);
}
catch (InterruptedException e)
{
[Link]();
}
}
}

public class Test implements Runnable


{
public static Thread thread1;
public static Test obj;

public static void main(String[] args)


{
obj = new Test();
thread1 = new Thread(obj);

// thread1 created and is currently in the NEW state.


[Link]("State of thread1 after creating it - " + [Link]());
[Link]();

// thread1 moved to Runnable state


[Link]("State of thread1 after calling .start() method on it - " +
[Link]());
}

public void run()


{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);

// thread1 created and is currently in the NEW state.


[Link]("State of thread2 after creating it - "+ [Link]());
[Link]();

// thread2 moved to Runnable state


[Link]("State of thread2 after calling .start() method on it - " +
[Link]());

// moving thread1 to timed waiting state


try
{
//moving thread1 to timed waiting state
[Link](200);
}
catch (InterruptedException e)
{
[Link]();
}
[Link]("State of thread2 after calling .sleep() method on it - "+
[Link]() );

try
{
// waiting for thread2 to die
[Link]();
}
catch (InterruptedException e)
{
[Link]();
}
[Link]("State of thread2 when it has finished it's execution - " +
[Link]());
}

}
Output:
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it -
TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED
Explanation: When a new thread is created, the thread is in the NEW state.
When .start() method is called on a thread, the thread scheduler moves it to Runnable
state. Whenever join() method is called on a thread instance, the current thread
executing that statement will wait for this thread to move to Terminated state. So, before
the final statement is printed on the console, the program calls join() on thread2 making
the thread1 wait while thread2 completes its execution and is moved to Terminated
state. thread1 goes to Waiting state because it is waiting for thread2 to complete it’s
execution as it has called join on thread2.

difference between multi-threading and multi-tasking


Multi-threading:
1) Multiple threads are executing at the same time at same or different part of
program
2) CPU switches between multiple threads
3) It is light weight process
4) Example: WEB SERVER
5) It is feature of process
6) Multi-threading is sharing of computing resources among threads of a
single process.
Multi-tasking:
1) Several programs are executed concurrently
2) CPU switches between multiple tasks and processes
3) It is heavy weight process
4) Example: WEB BROWSER
5) It is feature of OS
6) Multi-tasking is sharing of computing resources(CPU, memory, devices,
etc.) among processes

Common questions

Powered by AI

A Java thread can exist in the following states: New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated. In the New state, a thread is created but not yet started. In the Runnable state, the thread is ready to run and may be executing. In the Blocked state, a thread is waiting for a monitor lock to enter a synchronized block. The Waiting state occurs when a thread is waiting for another thread to complete a particular action, without a specified waiting time. Timed Waiting occurs when a thread is waiting with a timeout. The Terminated state occurs when a thread completes its execution or encounters an unhandled error. Each transition between states is managed by the thread scheduler .

The Waiting state occurs when a thread is waiting indefinitely for another thread to perform a specific action, such as calling Object.wait or Thread.join without a timeout. It stays in this state until it is reactivated by another thread. In contrast, the Timed Waiting state involves a defined timeout, as seen when a thread calls sleep or a condition wait with a timeout. Here, the thread transitions back to Runnable either when the timeout expires or it is notified beforehand .

The Blocked state in Java threading is critical for ensuring that only one thread can execute a synchronized block or method at any given time, thereby maintaining data integrity. When a thread enters the Blocked state due to a lock on a monitored resource, it prevents race conditions and data inconsistency, as only one thread accesses the critical section at a time. Program execution is affected by potentially delaying the thread until the resource becomes available, thus impacting throughput and efficiency in a multi-threaded application .

A thread transitions from the Blocked state to the Runnable state when the monitor lock it is waiting for becomes available. Initially, the thread enters the Blocked state as it tries to access a synchronized method or block that another thread holds. Once the lock is released, the thread scheduler selects a blocked thread to obtain the lock, thus moving it to the Runnable state where it can compete for execution time with other Runnable threads .

Yes, a thread can move directly from the Timed Waiting state to the Blocked state if, after being prematurely notified or if the timeout concludes, it tries to re-enter a synchronized block but encounters a monitor lock. In this case, it transitions to Blocked until the lock is available, after which it moves to Runnable .

When a thread is in the Terminated state, it has completed its execution and no longer consumes any CPU resources. This occurs after the thread has either finished running normally or encountered an unhandled error that leads to its shutdown .

Modern Java applications benefit from the Timed Waiting state in network operations by allowing threads to wait with a timeout for network resources, such as a response or connection. By leveraging methods like Thread.sleep or Object.wait with timeouts, threads can efficiently handle time-sensitive tasks, enabling applications to maintain responsiveness without busy-waiting, thereby freeing up CPU cycles for other tasks. This is especially useful in asynchronous network programming where waiting for network I/O can be extensive, but must be managed to avoid unnecessary blocking .

When a join method is invoked on a thread, the invoking thread enters the Waiting state. This occurs because join causes the current thread to pause execution until the thread on which join was called completes and enters the Terminated state. This synchronizes threads by ensuring one completes before another resumes .

The Java thread scheduler is responsible for determining when each thread in the Runnable state is allowed to execute. It allocates CPU time to each thread, providing a fixed time slice for each. The scheduling is preemptive, meaning that it actively decides which thread runs, based on factors such as thread priority, resource availability, and system architecture. Threads may execute concurrently, especially if utilizing multiple processors, but transitions are managed to ensure all threads have the opportunity to run .

Multithreading involves multiple threads executing within a single process, sharing the process's resources such as memory and CPU time. It's lightweight and specifically useful within applications like web servers. In contrast, multitasking involves multiple processes being executed concurrently. It requires more resource management from the operating system, as each process operates with its own allocated resources. For example, a web browser might run multiple processes for different tabs .

You might also like