java reentrantlock 基础
· 2 min read
背景
java 的基础内容
内容 | 备注 |
---|---|
java aqs | aqs 主要包括state 以及 阻塞 和queue |
aqs
state
:volatile
的int
变量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;
}
}