Java Thread States
The Thread class in Java represents a thread of execution in a program. Throughout its lifecycle, a thread can be in one of several states, defined as constants in the Thread class.
Thread States and Their Descriptions
NEW:
- The thread has been created but has not yet started.
- The thread object is instantiated, but system resources are not yet allocated.
RUNNABLE:
- The thread is ready to run after the
start()method is called. - It may be running or waiting for CPU time.
- The exact timing of execution is determined by the operating system’s thread scheduler.
- The thread is ready to run after the
BLOCKED:
- The thread is blocked, waiting to acquire a monitor lock.
- It occurs when a thread attempts to access a synchronized block or method currently held by another thread.
WAITING:
- The thread is waiting indefinitely for another thread to perform a particular action.
- This state is entered by calling methods like
Object.wait(),Thread.join(), orLockSupport.park().
TIMED_WAITING:
- The thread is waiting for another thread to perform an action for up to a specified waiting time.
- This state is entered by calling methods like
Thread.sleep(long millis),Object.wait(long timeout),Thread.join(long millis),LockSupport.parkNanos(long nanos), orLockSupport.parkUntil(long deadline).
TERMINATED:
- The thread has completed its execution.
- This occurs when the
run()method has finished execution or the thread has been interrupted.
Example to Demonstrate Thread States
Below is an example that demonstrates the transition of a thread through various states from creation to termination:
1 | public class ThreadStatesExample { |
Explanation of the Example
- NEW: The thread is in the
NEWstate after it is created but beforestart()is called. - RUNNABLE: After calling
start(), the thread moves to theRUNNABLEstate. - TIMED_WAITING: When
Thread.sleep(1000)is called within the thread, it enters theTIMED_WAITINGstate for 1000 milliseconds. - TERMINATED: After the thread finishes its execution or is interrupted, it moves to the
TERMINATEDstate.
Conclusion
The Thread class’s states help in understanding and managing thread execution in a Java program. By using methods like Thread.getState(), developers can effectively debug and manage multi-threaded applications. Understanding these states and their transitions is crucial for writing efficient and reliable concurrent code in Java.