Skip to main content

java reentrantlock 基础

· 2 min read

背景

java 的基础内容

内容备注
java aqsaqs 主要包括state以及 阻塞queue

aqs

  • state: volatileint变量
  • block(park/unpark) : 使用了linux的pthread_cond_wait , 也就是使用了条件变量
  • queue: 为什么需要queue , 因为条件变量唤醒queue中内容,queue一般放的是被阻塞的线程

可重入性

这里的可重入性指的是同一个线程可以多次对 Reentrantlock多次上锁

那么这个实现是怎么实现的呢?

其实就是state=0的时候,将当前线程Thread通过setExclusiveOwnerThread塞入Reentrantlock对应的同步器Sync

    abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;

/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
*/
@ReservedStackAccess
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;
}
}