有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

如果有人能举例说明这一机制,我们将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    a blocking semaphore

    ^{}类同时支持阻塞和非阻塞操作

    a blocking semaphore is initialised to zero rather than one

    您可以设置许可证的初始数量。如果将permits设置为1new Semaphore(1)),则可以在release之前acquire一次

    • 如果值为> 0,则某些acquire可能发生在release之前
    • 如果该值为<= 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
            }
        }
    
    }
    
  2. # 2 楼答案

    引用Semaphare类的javadoc

    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()调用

    这就是一切