Semaphore浅析

Semaphore

Semaphore是信号量 ,当线程acquire()获取一个信号量(permit)时才可以不阻塞,每个release方法归还一个信号量。

  • 构造函数
public Semaphore(int permits) {
        sync = new NonfairSync(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);
}

//这个也是AQS的方法,模板方法模式
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);
        }
}

//Semaphore的获取锁方法
protected int tryAcquireShared(int acquires) {
            return nonfairTryAcquireShared(acquires);
}
final int nonfairTryAcquireShared(int acquires) {
            for (;;) {
            //尝试获取锁,如果没有许可证了返回的是负数
            //如果获取许可证成功,返回剩余许可证(大于0)
                int available = getState();
                int remaining = available - acquires;
                if (remaining < 0 ||
                    compareAndSetState(available, remaining))
                    return remaining;
}
  • 释放许可证
//AQS的方法
public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
        //唤醒同步队列的首个线程节点
            doReleaseShared();
            return true;
        }
        return false;
}

//semaphore的方法,尝试释放锁(释放许可证),CAS成功返回ture
protected final boolean tryReleaseShared(int releases) {
            for (;;) {
                int current = getState();
                int next = current + releases;
                if (next < current) // overflow
                    throw new Error("Maximum permit count exceeded");
                if (compareAndSetState(current, next))
                    return true;
            }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值