ReentrantLock

ReentrantLock 是 Lock接口的实现类,跟synchorized功能一样,都是为了让线程安全。但是他比synchorized有更多的特性。


FairSync :公平锁操作
nonFairSync:非公平锁操作
tryLock():尝试获取锁
tryLock(long,TimeUnit):在指定的超时时间去获取锁
newCondition(): 根据设置的条件获取锁

unLock():释放锁

ReentrantLock 的加锁和释放锁都需要程序员手动去释放。 他的加锁和释放锁都是使用cas操作 根据锁的计数(count)实现。

tryLock:使用cas 和 状态值(state)来控制锁

 /**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();               // 获取当前拥有锁的线程
            int c = getState();                                                              // 0 :没有获得锁
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {                  // 使用unsafe.compareAndSwapInt 设置state=1
                    setExclusiveOwnerThread(current);                  // 把当前线程设置为拥有者
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {  // 如果其他线程获得锁,则判断拥有锁的线程是否是当前线程
                int nextc = c + acquires;                                          // 如果是 在state+1
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);                                                        // 更新state 的值
                return true;
            }
            return false;
        }
原文地址:https://www.cnblogs.com/zhangXingSheng/p/10810217.html