Thread life cycle states and thread issues

 The life cycle of threads in java

 

The initial state is also called the new state (New): when the thread object pair is created, it enters the new state, such as: Thread t = new MyThread();

The runnable state is also called the ready state (Runnable): when the start() method (t.start();) of the thread object is called, the thread enters the ready state. A thread in the ready state only means that the thread is ready and waiting for CPU scheduling execution at any time. It does not mean that the thread will be executed immediately after executing t.start();

Running state (Running): When the CPU starts to schedule the thread in the ready state, the thread can actually be executed at this time, that is, it enters the running state. Note: The ready state is the only entrance to the running state. That is to say, if a thread wants to enter the running state for execution, it must first be in the ready state;

Blocked state (Blocked): For some reason, the thread in the running state temporarily gives up the right to use the CPU and stops execution. At this time, it enters the blocked state. It will not have the opportunity to be called by the CPU again until it enters the ready state. to running status. According to the different reasons for blocking, the blocking state can be divided into three types: 1. Waiting blocking: The thread in the running state executes the wait() method to enter the waiting blocking state; 2. Synchronous blocking-the thread is getting When the synchronized synchronization lock fails (because the lock is occupied by other threads), it will enter the synchronization blocking state; 3. Other blocking-when the thread's sleep() or join() is called or an I/O request is issued, the thread will enter to a blocked state. When the sleep() state times out, join() waits for the thread to terminate or times out, or the I/O processing is completed, the thread returns to the ready state.

Death state (Dead) (End): The thread has finished executing or exited the run() method due to an exception, and the thread ends its life cycle.

The ready state is converted to the running state: when this thread obtains processor resources;

The running state transitions to the ready state: when this thread actively calls the yield() method or loses processor resources during running.

The running state is converted to the death state: when the execution body of this thread completes execution or an exception occurs.

What needs special attention here is: when the yield() method of the thread is called, the thread transitions from the running state to the ready state, but which thread in the ready state is scheduled by the CPU next has a certain degree of randomness, so A may occur. After the thread calls the yield() method, the CPU still schedules thread A.

Guess you like

Origin blog.csdn.net/a154555/article/details/128530532