java thread status + lock analysis

At the beginning, I posted a sketch of my thread state understanding (without drawing the end state):


        I believe that many small partners have more or less impressions of this kind of picture. Let's analyze the possible states of the thread and the reasons for the state changes. We all know that creating a new thread is very simple. You can create a new thread by inheriting Thread or implementing the Runnable/Callable interface. After calling the start() method, the thread enters the ready state, and can only wait for the system to schedule in the ready state. The running thread will enter the blocking state when it encounters ①t.join(), t.sleep(), or waiting for user input. Only when the thread in front of ②join finishes executing or the sleep time is up and the system gives it After the input, the blocking can be removed and returned to the ready state , or when the part locked by the synchonized keyword is encountered and the lock is not obtained, it will enter the lock pool state until the lock is obtained before returning to the ready state, of course, here It can also be understood as entering a synchronization queue (this will be discussed in detail later). Or it encounters the wait method of Object or LockSupport.park() and enters a waiting queue. When other threads holding the object execute the notify/notifyAll method or LockSupport.unpark() , it will enter the synchronization queue. Of course, there are also There are some timeout waiting states, which are similar to those that do not timeout, so I won't go into details here.

        In the previous description, the concept of lock is consistently mentioned. The lock is actually provided by the JVM layer. Each object has a monitor. When we hold the monitor of this object, we say that we hold the lock of this object. The synchonized keyword ensures that only one thread can hold the lock at the same time. Its specific implementation is completed by the monitorenter and monitorexit instructions, and these two instructions must appear in pairs. The running process in the waiting notification model of the thread is as follows (t1 is the waiting thread and t2 is the wake-up thread):

This is why we say that the wait method will release the lock.

Supplement: The difference between Object's wait/notify and LockSupport's park/unpark: Object's methods have strict order control. If the execution order changes, different results will be obtained, but park/unpark is for threads, regardless of the execution order. Changes or not, all thread code will eventually be executed.

        

Reference book: "The Art of Java Concurrent Programming"


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763379&siteId=291194637