1. /**
    2. * Sync object for non-fair locks
    3. */
    4. static final class NonfairSync extends Sync {
    5. private static final long serialVersionUID = 7316153563782823691L;
    6. /**
    7. * Performs lock. Try immediate barge, backing up to normal
    8. * acquire on failure.
    9. */
    10. final void lock() {
    11. if (compareAndSetState(0, 1))
    12. //设置当前加锁线程
    13. setExclusiveOwnerThread(Thread.currentThread());
    14. else
    15. acquire(1);
    16. }
    17. protected final boolean tryAcquire(int acquires) {
    18. return nonfairTryAcquire(acquires);
    19. }
    20. }

    if (compareAndSetState(0, 1)):对state变量做操作,代表了锁的一个状态。看一下state是否是0?如果是0的话,代表没人加过锁,此时我就可以加锁,把这个state设置为1。

    1. protected final boolean compareAndSetState(int expect, int update) {
    2. // See below for intrinsics setup to support this
    3. return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    4. }

    compareAndSetState(0, 1):相当于是在尝试加锁,底层原来是基于Unsafe来实现的,JDK内部使用的API,指针操作,基于cpu指令实现原子性的CAS,Atomic原子类底层也是基于Unsafe来实现的CAS操作。如果替换成功了,就会返回true,加锁失败就返回false。
    当加锁成功后就要setExclusiveOwnerThread(Thread.currentThread());

    1. /**
    2. * The current owner of exclusive mode synchronization.
    3. */
    4. private transient Thread exclusiveOwnerThread;
    5. protected final void setExclusiveOwnerThread(Thread thread) {
    6. exclusiveOwnerThread = thread;
    7. }