I’m trying to understand the different states of a thread in Java and how to observe these states throughout the thread lifecycle.
I have created a simple Java program to demonstrate thread states, but I’m not sure if I’m correctly observing the transitions between states. Here is my code:
public class ThreadStatesExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("Initial State: " + thread.getState()); // NEW
thread.start();
System.out.println("State after start(): " + thread.getState()); // RUNNABLE
thread.join();
System.out.println("State after join(): " + thread.getState()); // TERMINATED
}
}
**Expected Behavior:**
Clearly state what you expected your code to do. This helps others understand the desired outcome and compare it to the actual results.
**Error Messages or Unexpected Output:**
If there are error messages or unexpected behavior, provide these details. Include any stack traces, logs, or specific error codes you've encountered.
New contributor
LINGESWARAN V is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.