【问题标题】:Incrementing Semaphore permits, in Java在 Java 中增加信号量许可
【发布时间】:2012-04-05 01:18:00
【问题描述】:

我可以在 Java 中为信号量添加更多许可吗?

Semaphore s = new Semaphore(3);

在代码中的某处之后,我想将许可更改为 4。这可能吗?

【问题讨论】:

    标签: java multithreading concurrency semaphore


    【解决方案1】:

    是的。 release 方法(令人困惑地命名为 imo)可用于增加许可,因为来自文档:

    There is no requirement that a thread that releases a permit must 
    have acquired that permit by calling acquire. 
    Correct usage of a semaphore is established by programming convention
    in the application. 
    

    换句话说:

    semaphore.release(10);
    

    如果线程调用没有获得任何许可,将再添加 10 个许可。

    【讨论】:

    • +1 不错的观察。但是,这是特定于实现的吧?信号量不需要增加超过构造函数中定义的最大值,即实现可以在以后的版本中更改,删除此功能
    • @JohnVint - 它不是构造函数中的最大参数。 the initial number of permits available. This value may be negative, in which case releases must occur before any acquires will be granted. 负最大值有点傻..
    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多