Life Cycle of a Thread
Definition
The life cycle of a thread in Java represents the various states a thread transitions through from its creation until it completes its execution or is terminated by the Java Virtual Machine (JVM).
Main Content
1. New State
- A thread is in the "New" state when an instance of the
Threadclass is created using thenewkeyword, but thestart()method has not yet been invoked. - At this stage, the thread is just an object in the heap memory; no resources are allocated for execution.
2. Runnable State
- Once the
start()method is called, the thread moves to the "Runnable" state. - In this state, the thread is ready to run and is waiting for the thread scheduler to allocate CPU time slice.
3. Running State
- This occurs when the thread scheduler selects the thread from the runnable pool to execute its
run()method. - The thread actively executes the instructions defined within its task logic.
Working / Process
1. Waiting / Blocked / Sleeping
- A thread enters the "Blocked" state when it is waiting for a monitor lock to enter a synchronized block or method.
- It enters "Waiting" or "Timed Waiting" when it calls methods like
wait(),sleep(), orjoin(), pausing its execution until a specific condition is met or time elapses.
2. Execution Flow
- The CPU manages the context switching between multiple threads.
- The thread transitions back to "Runnable" once the waiting condition is satisfied or the sleep time expires.
3. Terminated (Dead)
- A thread enters the "Terminated" state when its
run()method completes naturally or due to an unhandled exception. - Once dead, a thread cannot be restarted.
[New]
|
start()
v
[Runnable] <---> [Running]
| |
(Wait/Sleep/Block) <---
|
[Terminated]
Advantages / Applications
- Improved Responsiveness: Allows applications to handle user input while performing heavy background tasks.
- Resource Optimization: Enables efficient utilization of multi-core processors by executing tasks in parallel.
- Task Decoupling: Facilitates the design of complex systems where different modules run independently without blocking one another.
Summary
The life cycle of a Java thread describes the states—New, Runnable, Running, Blocked, and Terminated—that a thread moves through during its existence. By managing these transitions, Java ensures efficient multitasking and concurrency in software development.
- New: Thread object created.
- Runnable: Ready for execution.
- Running: Currently executing code.
- Blocked/Waiting: Paused for resources or time.
- Terminated: Execution finished.
- Important Terms: Thread Scheduler, Context Switching, Monitor Lock, Runnable Interface.