image.png

semaphore.acquire()

  1. public void acquire() throws InterruptedException {
  2. sync.acquireSharedInterruptibly(1);
  3. }
  1. public final void acquireSharedInterruptibly(int arg)
  2. throws InterruptedException {
  3. if (Thread.interrupted())
  4. throw new InterruptedException();
  5. if (tryAcquireShared(arg) < 0)
  6. //AQS 的排队过程
  7. doAcquireSharedInterruptibly(arg);
  8. }
  1. protected int tryAcquireShared(int acquires) {
  2. for (;;) {
  3. if (hasQueuedPredecessors())
  4. return -1;
  5. int available = getState();
  6. int remaining = available - acquires;
  7. // 小于0 或者 CAS成功 ,如果小于0会短路,不执行cas操作
  8. if (remaining < 0 || compareAndSetState(available, remaining))
  9. return remaining;
  10. }
  11. }