each lock object has two queues, one is a thread queue , one is a blocking queue , the ready queue stores the threads that will acquire the lock , the blocking queue stores the blocked thread, and when one is awakened by the thread ( Notify) before it enters the ready queue and waits for a lock .
When beginning thread A executes the Account.add method for the first time, the JVM checks to see if the ready queue of the lock object account is already thread-waiting, if any, indicates that the lock of the account is already occupied, and because it is the first run, the ready queue of the account is empty. So thread A gets the lock and executes the Account.add method. If it happens at this point, thread B is going to execute the Account.withdraw method because thread A has acquired a lock that has not been released, so thread B will go into the account's ready queue and wait until the lock is available to execute.
A thread executes the critical section code procedure as follows:
1 Obtaining a Sync lock
2 Empty working memory
3 copy variable copy from main memory to working RAM
4 Calculation of these variables
5 Write a variable from working memory back to main storage
6 Release Lock
It can be seen that synchronized not only guarantees the concurrent order of multithreading, but also ensures the memory visibility of multithreading.
Instead of releasing the lock, the notify notifies a thread in the blocking queue of the lock object (blocked, which calls the Wait method actively), into the ready queue.
The way a thread releases locks, usually by actively invoking the wait method, synchronizing the code block to end the release lock resource.
Notifyall are all blocking threads in the wake-up blocking queue, and they all go into the ready queue, and the number of notify is one.
The synchronization code block ends the release of the lock resource, and a thread in the object-ready queue obtains the lock resource and begins the threading;
If you do not use notify then the thread in the blocking queue will always be blocked, even if the thread in the ready queue is executed, the thread in the blocking queue will always be in a blocking state
-------------- A thread release lock, it will be randomly identified from the ready queue ? (in doubt) a thread that gets the lock resource.
Each lock object has two queues, one is a ready queue, the other is a blocking queue