JDK源码--Semaphore(AQS子类)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_40632321/article/details/88687657
  • Semaphore称为计数信号量,允许n个任务同时访问某资源,可将信号量看做是在向外分发使用资源的许可证,只有成功获取许可证才能使用资源。
  • 支持公平与非公平两种获取方式。

初始化

public Semaphore(int permits) {
    sync = new NonfairSync(permits);
}

public Semaphore(int permits, boolean fair) {
    sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}

Sync(int permits) { //也是设置AQS状态
   setState(permits);
}

获取许可

public void acquire() throws InterruptedException {
    sync.acquireSharedInterruptibly(1); //获取一个许可
}

public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    if (tryAcquireShared(arg) < 0)
        doAcquireSharedInterruptibly(arg);
}

protected int tryAcquireShared(int acquires) {
    for (;;) {
        if (hasQueuedPredecessors())
            return -1;
        int available = getState();
        int remaining = available - acquires; //现存许可数扣减
        if (remaining < 0 ||
            compareAndSetState(available, remaining))
            return remaining;
    }
}

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); //回滚操作
    }
}

释放许可

public void release() { //同CountDownLatch
    sync.releaseShared(1);
}

公平与非公平方式的区别

  • 获取许可方式的不同
//公平锁的获取方式
protected int tryAcquireShared(int acquires) {
    for (;;) {
    	//区别在这里,如果有前驱节点,直接获取失败
        if (hasQueuedPredecessors()) 
            return -1;
        int available = getState();
        int remaining = available - acquires;
        if (remaining < 0 ||
            compareAndSetState(available, remaining))
            return remaining;
    }
}
展开阅读全文

没有更多推荐了,返回首页