Common Threads and Precautions in Java Programming
Thread Creation Methods
- Extending the Thread class: Extend the Thread class and override the run() method to define the concurrent execution process. Create an instance of this class and use the start() method to start the thread.
- Implementing the Runnable interface: Implement the Runnable interface and the run() method to define the concurrent execution process. Create an instance of this class, pass this instance as a parameter to the Thread constructor to create a Thread class, and use the start() method to start the thread.
Thread States
- After a thread is created using the new operator, it enters the New state (initial state).
- After the start() method is called, the thread transitions from the New state to the Runnable state (ready state). The start() method is called in the main() method (Running state).
- Once execution concludes, the thread enters the Dead state,
- in which it is eligible for garbage collection and cannot be restarted.
- If the thread calls the yield() method during running, the thread transitions from the Running state to the Runnable state.
Thread State |
Description |
|---|---|
New |
|
Runnable |
When a thread is in the Runnable state, the thread is ready and waiting to acquire CPU resources. |
Running |
Once the thread acquires CPU resources, it transitions to the Running state and begins executing the thread body, which is the content defined within the run() method. NOTE:
|
Block |
A thread enters the Block state in the following situations:
|
Dead |
Once the run() method completes execution, the thread enters the Dead state. NOTE:
Do not call the start() method on a Dead thread which cannot be executed again. Attempting to do so will cause the system to throw an IllegalThreadStateException. |
Parent topic: Programming