AQS在Semaphore的应用:
    在Semaphore中,State表示许可证的数量
    看tryAcquire方法,判断nonfairTryAcquireShared大于等于0的话,代表获取锁成功;
    tryAcquire方法具体实现:
    这里会先检查剩余许可证数量够不够这次需要的,用减法来计算,如果直接不够,那就返回负数,表示失败,如果够了,就用自旋加CompareAndSetState来改变state状态,改变成功就返回正数;或者是期间如果被其他人修改了导致剩余数量不够,那也返回负数代表获取失败;获取失败的陷入阻塞状态

    对于共享变量,对其进行修改时多线程环境下需要使用原子操作:
    与CountDownLatch区别:
    1.获取时,CountDownLatch获取根据构造函数的count,只要count>0就会阻塞,Semaphore获取permits,只要permits>=0获取更新permits成功就不会阻塞,只有当permits==0才会阻塞
    2.释放时,CountDownLatch,初始状态为0不去阻塞当然也不会去释放,每次循环遍历减1,并去判断原子更新后的值是否等于0,如果等于0,就返回true就释放,Semaphore当前剩余的个数加上需要释放的个数只要大于当前剩余的个数并且更新成功就可以释放,能释放一个是一个。

    1. public Semaphore(int permits) {
    2. sync = new NonfairSync(permits);
    3. }
    4. public void acquire() throws InterruptedException {
    5. sync.acquireSharedInterruptibly(1);
    6. }
    7. public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
    8. if (Thread.interrupted())
    9. throw new InterruptedException();
    10. if (tryAcquireShared(arg) < 0)
    11. doAcquireSharedInterruptibly(arg);
    12. }
    13. final int nonfairTryAcquireShared(int acquires) {
    14. for (;;) {
    15. int available = getState();
    16. int remaining = available - acquires;
    17. // 原子更新成功 直接返回剩余许可证个数 大于0不进入阻塞,当剩余个数小于0才阻塞
    18. if (remaining < 0 || compareAndSetState(available, remaining))
    19. return remaining;
    20. }
    21. }
    22. public void release(int permits) {
    23. if (permits < 0) throw new IllegalArgumentException();
    24. sync.releaseShared(permits);
    25. }
    26. public final boolean releaseShared(int arg) {
    27. if (tryReleaseShared(arg)) {
    28. doReleaseShared();
    29. return true;
    30. }
    31. return false;
    32. }
    33. protected final boolean tryReleaseShared(int releases) {
    34. for (;;) {
    35. int current = getState();
    36. int next = current + releases;
    37. if (next < current) // overflow
    38. throw new Error("Maximum permit count exceeded");
    39. if (compareAndSetState(current, next))
    40. return true;
    41. }
    42. }