AQS, the full name is AbstractQueuedSynchronizer, translated into Chinese as abstract queued synchronizer
AQS architecture:
Description: AQS maintains a volatile int state (representing shared resources) and a FIFO thread waiting queue (when multi-threaded contention for resources is blocked, it will enter the queue)
AQS defines two resource sharing methods: Exclusive (exclusive method) and Share (shared method)
Specifically in the java source code AbstractQueuedSynchronizer class:
-
protected boolean isHeldExclusively(): Whether the thread is monopolizing resources
-
tryAcquire/tryRelease: Try to acquire and release resources in an exclusive way
-
tryAcquireShared/tryReleaseShared: try to acquire and release resources in shared mode
ReentrantLock reentrant lock:
- The initial state is 0, which means the unlocked state
- When thread A acquires the lock, it will call tryAcquire() to monopolize the lock and state+1;
- After that, other threads will fail when tryAcquire again, until the A thread unlock() reaches state=0 (release the lock), other threads have the opportunity to acquire the lock;
- Before the A thread releases the lock, the A thread can repeatedly acquire the lock (state will accumulate), which is the concept of reentrant;
- It should be noted that: how many times the lock is acquired, how many times the lock must be released, so as to ensure that the state eventually returns to the 0 state;
CountDownLatch:
- The task is divided into N sub-threads to execute, and the state is also initialized to N (note: N needs to be consistent with the number of threads)
- These N sub-threads are executed concurrently. After each sub-thread is executed, countDown() is performed once, and the state will be reduced by 1 in CAS mode accordingly.
- When all child threads are executed (state==0), the thread will be called by LockSupport.unpark() (the change method is to directly use UNSafe, call the operating system level control thread method, so that the thread continues to execute)
- Then the main thread returns from the await function and continues execution;