In Java, a thread can be in one of several states in its lifecycle. Here are the different states of a Java thread:
- New: A thread is in the “new” state when it has been created, but has not yet started executing.
- Runnable: A thread is in the “runnable” state when it is ready to run, but the scheduler has not yet chosen it to be the active thread.
- Running: A thread is in the “running” state when it has been chosen by the scheduler to run on the CPU.
- Blocked: A thread is in the “blocked” state when it is waiting for a monitor lock to be released. This can happen, for example, when a synchronized block is entered by another thread.
- Waiting: A thread is in the “waiting” state when it is waiting for another thread to perform a particular action. For example, a thread may be waiting for a message to arrive on a queue.
- Timed Waiting: A thread is in the “timed waiting” state when it is waiting for a specified amount of time. For example, a thread may be waiting for a message to arrive on a queue for a maximum of 5 seconds.
- Terminated: A thread is in the “terminated” state when it has finished executing and will not run again.
It’s important to note that a thread can transition between these states throughout its lifetime. For example, a thread may start in the “new” state, transition to “runnable” when it is started, then to “running” when it is executed, and so on. Understanding these states is essential for managing threads in Java.
You may also like:
What are common multi-threading issues faced by Java Developers?
What are different states of a Thread? What does those states tell us?
What happens when wait() & notify() methods are called?
What is difference between sleep(), yield() and wait() method?
What is difference between Callable and Runnable Interface?