This is the 21st day of my participation in Gwen Challenge.

While the previous article covered several ways to create threads, this article will take a thorough look at the life cycle of threads.

A, problem,

Before we get into the life cycle of threads, let’s think about a few issues.

  • What are the life cycle states of a thread, and what is the state flow?
  • TIME-WAITING WAITING What’s the difference?
  • BLOCKED*WAITINGWhat are the state differences?
  • sleep,wait,join,yieldWhat are the effects of each function execution on the thread?

With those questions in mind, read on.

Second, the life cycle of threads

There are six states in the entire life cycle of a thread, from creation to destruction. Include:

  • NEW Initial state. The thread is created, but cannot return to this state after the state is changed to RUNNABLE before START is executed.

    A thread that has not yet started is in this state.

  • The RUNNABLE state actually contains two sub-states, one is ready and the other is running.

    A thread executing in the Java virtual machine is in this state.

  • The state of being BLOCKED is a unique state of waiting, especially for a lock. A blocked state indicates that the thread has relinquished CPU usage and entered the wait state.

    A thread that is blocked waiting for a monitor lock is in this state.

  • Time-waiting Indicates the timeout WAITING status. After a timeout, the system automatically returns. Generated when a thread waits for another thread to perform an action within a specified wait time.

    A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

  • WAITING WAITING state: No timeout WAITING state. Generated when a thread is waiting for another thread to perform an action.

    A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

  • TERMINATED state, which indicates that the thread is TERMINATED and is the end state of the thread.

    A thread that has exited is in this state.

This diagram fully reflects the flow of state conditions from thread creation of NEW state to thread termination of TERMINATED state. There is no need to elaborate. See the Java documentation for the functions called.


Brother boy, don’t panic to go! Leave a thumbs-up and comment on the discussion. Welcome to the column face interview don’t panic | Java concurrent programming, a raise don’t have to worry about the interview. Also welcome to pay attention to me, must be a longer better man.