ReentranReadWriteLock的WriteLock源码解读

//ReentrantReadWriteLock的WriteLock
//WriteLock的lock方法

public void lock() {
            sync.acquire(1);
        }

 public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }


 protected final boolean tryAcquire(int acquires) {
          
            Thread current = Thread.currentThread();
	    //获取state状态
            int c = getState();
            int w = exclusiveCount(c);
	    //如果c不为0说明当前有线程获取了锁
            if (c != 0) {
                // (Note: if c != 0 and w == 0 then shared count != 0)
		//当前线程不是当前正在运行的独占线程
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // Reentrant acquire
                setState(c + acquires);
                return true;
            }
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }


 final boolean writerShouldBlock() {
            return false; // writers can always barge
        }


//WriteLock简单来说就是判断当前有没有线程占用锁,有则入队等待唤醒。没有直接占用运行。


WriteLock的unlock方法:
 public void unlock() {
            sync.release(1);
        }

 public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
//设置状态以及将独占线程设置为null
protected final boolean tryRelease(int releases) {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            int nextc = getState() - releases;
            boolean free = exclusiveCount(nextc) == 0;
            if (free)
                setExclusiveOwnerThread(null);
            setState(nextc);
            return free;
        }





//WriteLock的其他方法和Reentrant基本一致。WriteLock本身就相当于ReentrantLock互斥锁。

相关推荐