/**
* Sync object for non-fair locks
*/
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
*/
final void lock() {
if (compareAndSetState(0, 1))
//设置当前加锁线程
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
if (compareAndSetState(0, 1)):对state变量做操作,代表了锁的一个状态。看一下state是否是0?如果是0的话,代表没人加过锁,此时我就可以加锁,把这个state设置为1。
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
compareAndSetState(0, 1):相当于是在尝试加锁,底层原来是基于Unsafe来实现的,JDK内部使用的API,指针操作,基于cpu指令实现原子性的CAS,Atomic原子类底层也是基于Unsafe来实现的CAS操作。如果替换成功了,就会返回true,加锁失败就返回false。
当加锁成功后就要setExclusiveOwnerThread(Thread.currentThread());
/**
* The current owner of exclusive mode synchronization.
*/
private transient Thread exclusiveOwnerThread;
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}