设置同步状态,利用CAS操作。

// CAS操作:如果当前状态值等于期望值,则自动将同步状态设置为给定的更新值
protected final boolean compareAndSetState(int expect, int update)

进入tryLock,实际上是非公平锁的实现(非公平锁:不能保证正在排队的线程能拿到锁,因为可能被新来的线程抢走

public boolean tryLock() {
return sync.nonfairTryAcquire(1);
} 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;
}

进入lock,实际上是公平锁的实现(公平锁:老的线程在排队,新来的线程也一样要排队,不能抢占

public void lock() {
sync.lock();
}
final void lock() {
acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) // 如果获取不到锁,就放进等待队列(addWaiter),然后阻塞直到成功获取到锁
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// 唯一与非公平锁不同的是:先判断等待队列是否有等待的线程,没有的话再更改同步状态。否则返回false。
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;
}

tryLock和lock不同点

1. tryLock不管拿到拿不到都直接返回;lock如果拿不到则会一直等待。

2. tryLock是可以中断的。

05-11 20:30