对于java基于AQS实现锁的疑惑

基于AQS实现的锁,依赖于状态变量的CAS操作

/** * 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 <tt>volatile</tt> read * and write. * * @param expect the expected value * @param update the new value * @return 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); }

方法compareAndSwapInt:

其中this–>AbstractQueuedSynchronizer , stateOffset–>unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state"));

疑惑的地方在于:stateOffset是static final long型的,也就是所有的AbstractQueuedSynchronizer 对象共享此变量?

当多个线程访问同一lock对象且系统中仅有一个Lock对象的时候好像还可以,

如果有多个lock对象,那么不同的lock看到岂不是同一个stateOffset?

那这样怎么区分不同的lock呢?

在你生活出现失意和疲惫时能给你一点儿力量和希冀,只愿你幸福快乐。

对于java基于AQS实现锁的疑惑

相关文章:

你感兴趣的文章:

标签云: