Give a briefing on the life cycle of a thread, I hope you can expand on it from the perspective of Java source code
In Java, a thread is a lightweight process that allows concurrent execution of code. Understanding the life cycle of a thread is crucial for effective multithreading in Java. The life cycle of a thread can be divided into several states, each representing a specific stage in the thread's life. Below is a detailed briefing on the thread life cycle, along with relevant Java source code examples.
New (Born) State:
Thread
class is created.Example:
Thread thread = new Thread(new MyRunnable());
// The thread is in the New state
Runnable State:
start()
method is called. In this state, the thread is ready to run and waiting for CPU time.Example:
thread.start(); // The thread is now in the Runnable state
Blocked State:
Example:
synchronized (lock) {
// Thread may enter Blocked state if another thread holds the lock
}
Waiting State:
Object.wait()
, Thread.join()
, or LockSupport.park()
.Example:
synchronized (lock) {
lock.wait(); // The thread is now in the Waiting state
}
Timed Waiting State:
Thread.sleep(milliseconds)
, Object.wait(milliseconds)
, or Thread.join(milliseconds)
.Example:
Thread.sleep(1000); // The thread is now in the Timed Waiting state for 1 second
Terminated State:
Example:
// After the run() method completes, the thread enters the Terminated state
The life cycle of a thread can be visualized as follows:
New -> Runnable -> Running -> Terminated
| ^
| |
v |
Blocked <----|
|
v
Waiting <----|
|
v
Timed Waiting
start()
is called.wait()
, join()
, or LockSupport.park()
.sleep()
, wait(milliseconds)
, or join(milliseconds)
.run()
method completes or an unhandled exception occurs.Understanding the life cycle of a thread in Java is essential for writing efficient multithreaded applications. By managing the states and transitions effectively, developers can optimize resource usage and improve application performance. The Java Thread
class and the Runnable
interface provide the necessary tools to create and manage threads, allowing for concurrent execution of tasks.