preface
The last blog introduced how to stop a thread correctly. This blog began to introduce the life cycle of a thread, which is also a few states of a thread that are often mentioned in interviews. At the same time, we made a summary for the transformation of these states.
Which states
I've read some summaries about the status of threads. It's too complicated to say anything. Even in the summary diagram in some blog posts, the names of states are different. In fact, in the source code of Thread class, there are several Thread states, and the corresponding enumeration types are defined one by one. The details are as follows. Several Thread states in Java can be summarized according to this
public enum State { /** * Thread state for a thread which has not yet started. */ NEW, /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */ RUNNABLE, /** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ BLOCKED, /** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called <tt>Object.wait()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on * that object. A thread that has called <tt>Thread.join()</tt> * is waiting for a specified thread to terminate. */ WAITING, /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }
Authoritative conclusion - there are six states for Java threads
state | Specific meaning |
---|---|
NEW | The corresponding thread object is just New, and the start method has not been called |
RUNNABLE | Threads that are executing or waiting for the CPU to schedule execution are in Runnable status |
BLOCKED | When a thread wants to enter the code block modified by synchronize, but cannot obtain the lock, it is in the BLOCKED state (the BLOCKED state specifically refers to the BLOCKED state when entering synchronize) |
WAITING | Because after calling Object.wait(), Thread.join(), LockSupport.park(), the thread enters the blocking state. At this time, the thread waits for other threads to wake up |
TIMED_WAITING | Because the call to sleep(), Object.wait(long), join(long), LockSupport.parkNanos, LockSupport.parkUntil and other methods enters the timing waiting state, the thread will wake up automatically when the time expires |
TERMINATED | The termination state of the thread. The thread will enter this state after running |
It should be noted that there are only these six thread states in Java, and there is no other relevant statement.
State transition diagram
Based on the above, we draw the state transition diagram of threads
Related code examples
Examples of NEW, Runnable, and Terminated States
/** * autor:liman * createtime:2021/9/11 * comment:Displays the new runnable terminated status of the thread */ @Slf4j public class NewRunnableTerminated implements Runnable { @Override public void run() { for (int i = 0; i < 10000; i++) { System.out.println(i); } System.out.println(Thread.currentThread().getState()); } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new NewRunnableTerminated()); System.out.println(thread.getState());//NEW thread.start(); System.out.println(thread.getState());//At the beginning, there may not be resources, but also RUNNABLE Thread.sleep(5); System.out.println(thread.getState());//The printing thread is also running Thread.sleep(10); System.out.println(thread.getState());//TERMINATED } }
As mentioned in many previous materials, thread running and waiting running are not in the same state, which is not the case in the above examples.
About BLOCKED, WAITING, TIME_WAITING is an example of three states
/** * autor:liman * createtime:2021/9/11 * comment:Demonstrate three states of thread blocked waiting TimeWaiting */ @Slf4j public class BlockedWaitingTimedWaiting implements Runnable{ @Override public void run() { sync(); } private synchronized void sync(){ try { Thread.sleep(1000);//sleep status is timed_ Status of waiting wait();//After the thread executes sleep, it will enter the wait state } catch (InterruptedException e) {//Although interrupt exceptions should not be handled in submethods, they are optional here for demonstration purposes e.printStackTrace(); } } public static void main(String[] args) { BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting(); Thread thread1 = new Thread(runnable); thread1.start(); Thread thread2 = new Thread(runnable); thread2.start(); try { //The main thread pauses to get the latest status of the thread Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } //Print out TIME_WAITING because thread 1 is sleep ing log.info("The current status of thread 1 is:{}",thread1.getState()); //Thread 2 wants to get the sync lock, but cannot. Here, thread 2 is in the BLOCKED state log.info("The current status of thread 2 is:{}",thread2.getState()); try { //The main thread pauses so that thread 1 enters the latest state of the wait state Thread.sleep(1300); } catch (InterruptedException e) { e.printStackTrace(); } //Since the wait method is called, thread 1 is in the wait state log.info("The current status of thread 1 is:{}",thread1.getState()); } }
The operation results are as follows:
Some interview questions
1. What are the states of a thread (what is the life cycle of a thread)
6. You can answer them according to the diagram. It should be noted that there is no so-called Running status.
2. Does blocking just mean BLOCKED?
Not only the BLOCKED status, but also the BLOCKED status, WAITING status and time_ The WAITING state is called blocking state
summary
Briefly summarize several Thread states. The next summary will summarize some methods in the Thread class, such as wait and join.