Java并发编程-ReentrantReadWriteLock

  基于

protected final int tryAcquireShared(int unused) {             Thread current = Thread.currentThread();//当前线程            int c = getState();                 //持有写锁的线程可以获取读锁            if (exclusiveCount(c) != 0 &&  //已经分配了写锁                getExclusiveOwnerThread() != current) //当前线程不是持有写锁的线程                return -1;             int r = sharedCount(c); //读锁获取次数            if (!readerShouldBlock() && //由子类根据公平策略实现决定是否可获取读锁                r < MAX_COUNT && //读锁获取次数小于最大值                compareAndSetState(c, c + SHARED_UNIT)) {//更新读锁状态                if (r == 0) {//读锁的第一个线程 此时可以不用记录到ThreadLocal                    firstReader = current;                      firstReaderHoldCount = 1; //避免查找ThreadLocal 提升效率                } else if (firstReader == current) {//读锁的第一个线程重入                    firstReaderHoldCount++;                 } else {//非读锁的第一个线程                    HoldCounter rh = cachedHoldCounter; //下面为重入次数更新                    if (rh == null || rh.tid != getThreadId(current))                         cachedHoldCounter = rh = readHolds.get();                     else if (rh.count == 0)                         readHolds.set(rh);                     rh.count++;                 }                 return 1;             }             return fullTryAcquireShared(current); //获取读锁失败 循环重试        } final int fullTryAcquireShared(Thread current) {             HoldCounter rh = null;             for (;;) {                 int c = getState();                 if (exclusiveCount(c) != 0) {//获取到写锁                    if (getExclusiveOwnerThread() != current)                          return -1; //非写锁线程获取失败                     // else we hold the exclusive lock; blocking here                     // would cause deadlock.                } else if (readerShouldBlock()) {                     // Make sure we're not acquiring read lock reentrantly                    if (firstReader == current) {                         // assert firstReaderHoldCount > 0;                    } else {                         if (rh == null
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信