preface

Today we’ll look at the life cycle of threads. We don’t seem to attach much importance to the thread lifecycle when we learn about multithreading, either because we think it’s easy, or because we’re rarely asked about it in interviews, so it doesn’t feel very important. This is not true. Being familiar with the states and transitions between them in a thread’s life cycle not only helps you understand how threads work, but also helps you understand the locks behind them.

Before we get to the thread lifecycle, let me ask you a question: what is the state of a thread when using blocking IO to wait for user input?

The immediate answer you might give is blocked. Is it really so? If you’re interested, you can now write a program to verify that and see what ThreadState returns. Yes, it returns Runnable instead of Blocked. Why? I’ll elaborate on that later, but keep it in suspense

Operating system thread lifecycle

JVM threads run on operating system threads, which are further encapsulated. Let’s start by looking at the life cycle of the common operating system thread

The process is as follows:

  • First we create a thread whose state is New;
  • When the thread starts, its state becomes Ready. Note that it is not actually working, but waiting for a CPU slice to be allocated.
  • After the time slice is allocated, the state changes to Running, and then the work really starts.
  • If no sleep or blocking occurs, the thread ends and state is Terminated.
  • If you want to perform some hibernation or blocking operation, the thread is Blocked;
  • After hibernation or blocking, the thread cannot return to the Running state directly. Instead, it becomes Ready first, and then becomes Running after the time slice is acquired

Note: threads that are Blocked can be Terminated and become Terminated. We’ll talk about how to gracefully interrupt a thread, right

conclusion

The life cycle of operating system threads, described above, is divided into five states. The transition between states is also explained. In the next section, we’ll take a look at the JVM thread life cycle and focus on the differences and transitions between JVM thread states.

Again, it is important to be familiar with transitions between JVM thread states, which will help you understand “locking” later