来,一览多线程抢占式获取state过程
AbstractQueuedSynchronizer基于ReentrantLock实现!
* <p>To enqueue into a CLH lock, you atomically splice it in as new * tail. To dequeue, you just set the head field. * <pre> * +------+ prev +-----+ +-----+ * head | | <---- | | <---- | | tail * +------+ +-----+ +-----+ * </pre>
/**
* The synchronization state.
*/
private volatile int state;
/**
* Atomically sets synchronization state to the given updated
* value if the current state value equals the expected value.
* This operation has memory semantics of a {@code volatile} read
* and write.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that the actual
* value was not equal to the expected value.
*/
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
ReentrantLock 可重入,当线程1 初次获取到锁时,将state改为1;线程1重如的话,state会+1;释放锁时减1,直至为0,并唤醒等待队列的线程,非公平的抢占state!
总而言之: 一堆线程抢占共享的state!