compareAndSetState(0, 1):由于现在的情况是可重入的加锁,那么这个cas一定是fasle,接下来就要走这个acquire方法。
    image.png
    这个acquire就是AQS的方法,随后进入这个tryAcquire方法中,这个tryAcquire是AQS的一个空实现,具体是由子类来实现的,因此就是NonfairSync类中的tryAcquire
    image.png
    nonfairTryAcquire流程:

    1. 先获取到当前的线程 -> 线程1
    2. 获取state变量值的过程,JDK源码里大量的运用了volatile,可见性的问题,保证一些关键变量,修改 -> 读取的可见性
    3. 为什么会有这段代码呢?其实进入到这里,代表他之前一定是看到state != 0,才会进入到这里,为了保证代码的健壮性,当前线程之前加锁失败了继续走别的流程了,走着走着万一别的线程释放锁了,当前线程就没有必要再放入队列中了,直接加锁就完事了。
    4. 代表当前没有人释放锁,再次判断,如果执行这个方法的线程 = exclusiveOwnerThread(加锁的线程),就代表现在要做一个重入锁的操作了,之前他自己加过锁,然后在这里他就再次加锁
    5. 此时,c = 1,nextc = c(1) + acquires(1) = 2,其实就是代表了一个线程可重入加锁了1次,2代表了加锁的次数。
    6. 修改这个state的值,volatile保证了可见性
      1. /**
      2. * Performs non-fair tryLock. tryAcquire is implemented in
      3. * subclasses, but both need nonfair try for trylock method.
      4. */
      5. final boolean nonfairTryAcquire(int acquires) {
      6. //1.
      7. final Thread current = Thread.currentThread();
      8. //2.
      9. int c = getState();
      10. //3.
      11. if (c == 0) {
      12. if (compareAndSetState(0, acquires)) {
      13. setExclusiveOwnerThread(current);
      14. return true;
      15. }
      16. }
      17. //4.
      18. else if (current == getExclusiveOwnerThread()) {
      19. //5.
      20. int nextc = c + acquires;
      21. if (nextc < 0) // overflow
      22. throw new Error("Maximum lock count exceeded");
      23. //6.
      24. setState(nextc);
      25. return true;
      26. }
      27. return false;
      28. }