ReentrantLock的底层是aqs,aqs的加锁是通过CAS操作的, 因为aqs大量使用CAS所以性能比syncionzed的性能好很多
AQS图解
ReentrantLock的底层是Sync这个类 Sync是AQS的子类
public ReentrantLock() {
sync = new NonfairSync();
}
lock()的底层还是CAS
cas可以无锁化的保证原子性
final void lock() {
//如果加锁成功 cas操作使得state变为1.
if (compareAndSetState(0, 1))
//独占锁
setExclusiveOwnerThread(Thread.currentThread());
else
//如果state!=1 健壮性考虑,防止其他线程释放锁
acquire(1);
}
//如果state!=1
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//代表了线程在可重入的加锁
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
底层还是基于unsafe