AQS
AbstractQueuedSynchronizer
关注点
Node
先进先出的队列
volatile int state
标记当前锁是否被获取或者获取的次数(可重入锁)
tryAcquire()
排它锁使用的尝试获取锁方法,需要子类重写
tryRelease()
排它锁使用的尝试释放锁方法,需要子类重写
tryAcquireShared()
共享锁使用的尝试获取锁方法,需要子类重写
tryReleaseShared()
共享锁使用的尝试释放锁方法,需要子类重写
ReentrantLock
有一个成员变量 Sync sync (同步器)
Sync 实现了AQS接口
1.实现了Lock接口
2.使用了AQS同步器
实例代码
private Lock lock = new ReentrantLock();
public void method() {
lock.lock();
try {
Thread.sleep(1000);
System.out.println("hello");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
ReentrantLock 构造方法
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
lock()
public void lock() {
sync.lock();
}
FairSync.lock()
final void lock() {
acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
NonfairSync.lock()
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
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)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
unlock()
不管是公平锁还是非公平锁都是用的一个方法
public void unlock() {
sync.release(1);
}
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}