ReentranReadWriteLock的WriteLock源码解读_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > ReentranReadWriteLock的WriteLock源码解读

ReentranReadWriteLock的WriteLock源码解读

 2017/8/2 15:39:24  红领巾丶  程序员俱乐部  我要评论(0)
  • 摘要://ReentrantReadWriteLock的WriteLock//WriteLock的lock方法publicvoidlock(){sync.acquire(1);}publicfinalvoidacquire(intarg){if(!tryAcquire(arg)&&acquireQueued(addWaiter(Node.EXCLUSIVE),arg))selfInterrupt();}protectedfinalbooleantryAcquire
  • 标签:源码 DWR
class="java" name="code">
//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互斥锁
发表评论
用户名: 匿名