This is the seventh day of my participation in the More text Challenge. For details, see more text Challenge

This is a basic question about threading, but it’s still asked by many interviewers, and if it gets stuck, you’re less likely to pass.

Let’s take a look!

When a thread is created and started, it is not followed by the execution of a code block. There is a process, which is the life cycle of a thread from beginning to end.

The whole network actually has two versions of the lifecycle explanation, much the same but little different.

Five kinds of state

One theory is that there are five states: New, Runnable, Running, Blocked, and Dead.

Six state

Another talk is of six states: New, Runnable, Terminated, Blocked, Waiting, and Time_Waiting.

Note: Runnable includes both the Running state and the Ready state.

In five or six, in fact is very clear illustrates a thread a process from birth to death, and the interviewer to ask this question, of course, is not so simple, there lies a more important point, that is the state can be switch to each other, through which methods and then look at the below.

I will not talk about the five states here, because I found a flow chart with six states lying in the flow chart notes. Today I will focus on the state switching under the six states.

The above first!

Illustration to explain

  1. The Thread is switched from New to Runnable by the thread.start () method, which is the first step in starting the Thread.

  2. From the Runnable state to the Blocked state, the thread is locked when it needs to execute a block of code, or switches to the Blocked state when it makes an I/O request. When the lock is released or the IO request completes, the thread switches back from the Blocked state to the Runnable state.

  3. To go from the Runnable state to the Waiting state, you need to call the wait() method in the thread block to make the current thread wait. When the notify() or notifyAll() method is called, the thread switches back from Waiting to Runable.

  4. To go from a Runnable state to a Time_Waiting state, you need to call the sleep() method in the thread block. Because the sleep method needs to pass a time argument, it will cause the current thread to wait for a certain period of time. Just wait for the time to timeout and the thread will switch back from the Time_Waiting state to the Runnable state.

  5. The transition from the Runnable state to the Terminated state indicates that the thread is dead. Once the thread is finished, it will be withdrawn from the thread pool or destroyed.

The knowledge of thread pool can be discussed in detail later. That’s all for today. Although the knowledge this time is basic, it is equally important, whether it is for interview or daily work.