Java 中的阻塞信号量是什么?

What is a blocking semaphore in Java?

根据我的理解,阻塞信号量被初始化为零而不是一个,其工作方式是任何执行 P(S) 操作的线程都将阻塞,直到被 V(S) 首先释放。

任何人都可以用例子解释这个机制,任何帮助将不胜感激

引用 Semaphare 的 javadoc class:

permits - the initial number of permits available. This value may be negative, in which case releases must occur before any acquires will be granted.

并且:

Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer.

因此,假设您使用 -1 初始化,信号量将阻塞 acquire() 调用,直到 release() 进来。

从这个意义上讲:您只需执行 semaphore = new Sempahore(-1),您会发现 semaphore.acquire() 将阻塞,直到其他线程完成 semaphore.release() 调用。

仅此而已。

a blocking semaphore

java.util.concurrent.Semaphore class 支持阻塞和 non-blocking 操作。

a blocking semaphore is initialised to zero rather than one

您设置了初始许可数。如果您将 permits 设置为 1 (new Semaphore(1)),您可以在 release.

之前 acquire 一次
  • 如果值为> 0,则release之前可能会发生一些acquire
  • 如果值为 <= 0,则必须在调用 acquire 之前发生一些 release

记录在 JavaDoc:

This value may be negative, in which case releases must occur before any acquires will be granted.


class Example {

    public static void main(String[] args) throws InterruptedException {
        final Semaphore s1 = new Semaphore(0);
        s1.acquire(); 
        // the thread is disabled
        // no permit is available
        // a blocking operation

        final Semaphore s2 = new Semaphore(1);
        s2.acquire();
        // returns immediately
        // one permit was available

        final Semaphore s3 = new Semaphore(0);
        if (s3.tryAcquire()) {
            // a non-blocking operation
            // returns false immediately
        }
    }

}