public interface ReadWriteLock {
Lock readLock(); //获取读锁
Lock writeLock(); //获取写锁
}
//ReentrantReadWriteLock
private final ReentrantReadWriteLock.ReadLock readerLock;
private final ReentrantReadWriteLock.WriteLock writerLock;
final Sync sync;
public ReentrantReadWriteLock(){
this(false); //默认非公平锁
}
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync(); //锁类型(公平/非公平)
readerLock = new ReadLock(this); //构造读锁
writerLock = new WriteLock(this); //构造写锁
}
……
public ReentrantReadWriteLock.WriteLock writeLock0{return writerLock;}
public ReentrantReadWriteLock.ReadLock readLock0{return ReaderLock;}
//ReentrantReadWriteLock$ReadLock
public static class ReadLock implements Lock {
protected ReadLock(ReentrantReadwritLock lock) {
sync = lock.sync; //最后还是通过Sync内部类实现锁
}
…… //它实现的是Lock接口,其余的实现可以和ReentrantLock作对比,获取锁、释放锁等等
}
//ReentrantReadWriteLock$WriteLock
public static class WriteLock implemnts Lock {
protected WriteLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
…… //它实现的是Lock接口,其余的实现可以和ReentrantLock作对比,获取锁、释放锁等等
}
//ReentrantReadWriteLock$Sync
protected final boolean tryAcquire(int acquires) {
Thread current = Thread.currentThread;
int c = getState(); //获取state状态
int w = exclusiveCount(c); //获取写状态,即 state & 0x00001111
if (c != 0) { //存在同步状态(读或写),作下一步判断
if (w == 0 || current != getExclusiveOwnerThread()) //写状态为0,但同步状态不为0表示有读状态,此时获取锁失败,或者当前已经有其他写线程获取了锁此时也获取锁失败
return false;
if (w + exclusiveCount(acquire) > MAX_COUNT) //锁重入是否超过限制
throw new Error(“Maxium lock count exceeded”);
setState(c + acquire); //记录锁状态
return true;
}
if (writerShouldBlock() || !compareAndSetState(c, c + acquires))
return false; //writerShouldBlock对于非公平锁总是返回false,对于公平锁则判断同步队列中是否有前驱节点
setExclusiveOwnerThread(current);
return true;
}
//ReentrantReadWriteLock$FairSync
final boolean writerShouldBlock() {
return hasQueuedPredecessors();
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有