AbstractQueuedSynchronizer类方法

源码:

     public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
             //子类方法
             return tryAcquireShared(arg) >= 0 ||  doAcquireSharedNanos(arg, nanosTimeout);
         }
      /** * Acquires in shared interruptible mode. * @param arg the acquire argument */
      private void doAcquireSharedInterruptibly(int arg)   
         throws InterruptedException {   
              final Node node = addWaiter(Node.SHARED);  
              boolean failed = true;   
              try {      
                        for (;;) {           
                          final Node p = node.predecessor();           
                             if (p == head) {               
                               int r = tryAcquireShared(arg);               
                               if (r >= 0) {                   
                                 setHeadAndPropagate(node, r);                   
                                 p.next = null;
                                 // help GC     
                                 failed = false;                  
                                 return;               
                                   }           
                                }           
                                if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())               
                                    throw new InterruptedException();       
                                 }   
                          } finally {       
                             if (failed)           
                                cancelAcquire(node);   
                         }
                      }
                  }
               }
           }
       }

 

  添加等待

  private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }

 

posted @ 2020-09-01 16:34  小窝蜗  阅读(92)  评论(0)    收藏  举报