Semaphore

239 阅读2分钟

Semaphore管理一系列许可证;通过acquire方法获取许可证,如果获取到许可证,那么直接返回,否则进入阻塞状态;通过release释放许可证,释放的时候如果有线程因为调用acquire处于阻塞状态,将会唤醒一个线程。一般用于管理一个公共的资源,并且同一时间只允许指定数量的线程访问的场景。 java.util.concurrent中的并发类基本上都是用的是AQS(AbstractQueuedSynchronizer)来实现的。

1 构造函数

以下是Semaphore构造函数:

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

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

这两个构造函数的差别是:是否指定锁的公平性。公平锁是指按照申请锁的顺序获取锁,非公平锁是指当所资源被释放时,正在申请此资源的多个线程争抢锁,谁抢到归谁。

2 acquire

请求一个许可证,如果当前Semaphore中存在足够的许可证,那么此方法会立即返回,如果当前Semaphore中没有足够的许可证,那么调用此方法的线程将进入阻塞状态直到其他线程通过release释放了许可证。 以下是公平锁的acquire代码:

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);
    }
}

3 release

release方法的作用是增加一个许可证,这个操作会唤醒一个通过acquire方法阻塞的线程。

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

public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}

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;
    }
}

private void doReleaseShared() {
    for (;;) {
        Node h = head;
        if (h != null && h != tail) {
            int ws = h.waitStatus;
            if (ws == Node.SIGNAL) {
                if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                    continue;            // loop to recheck cases
                unparkSuccessor(h);
            }
            else if (ws == 0 &&
                     !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                continue;                // loop on failed CAS
        }
        if (h == head)                   // loop if head changed
            break;
    }
}

4 示例

以下示例创建了3个线程,他们都尝试获取semaphore对象的许可证,因为只有一个许可证,所以同一时间只有一个线程能执行doTask方法;当一个线程执行完以后会唤醒一个等待的线程继续执行。

public static void main(String[] args) {
    Semaphore semaphore = new Semaphore(1);
    for (int i = 0; i < 3; i++) {
        String name = "p-"+i;

        Thread thread = new Thread(() -> {
            try {
                System.out.println("时间="+DateUtil.getCurrentTime()+" 用户"+name+" 开始获取资源");
                semaphore.acquire();
                doTask(name);
                semaphore.release();
                System.out.println("时间="+DateUtil.getCurrentTime()+" 用户"+name+" 资源释放完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}

private static void doTask(String name){
    System.out.println("时间="+DateUtil.getCurrentTime()+" 用户"+name+" 开始使用资源,执行任务");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

以下是输出结果,从输出结果中可以看到和示例开始的分析一致。

时间=10:40:07:703 用户p-2 开始获取资源
时间=10:40:07:741 用户p-2 开始使用资源,执行任务
时间=10:40:07:703 用户p-1 开始获取资源
时间=10:40:07:703 用户p-0 开始获取资源
时间=10:40:10:745 用户p-1 开始使用资源,执行任务
时间=10:40:10:745 用户p-2 资源释放完成
时间=10:40:13:748 用户p-1 资源释放完成
时间=10:40:13:748 用户p-0 开始使用资源,执行任务
时间=10:40:16:751 用户p-0 资源释放完成