简体   繁体   中英

Incrementing Semaphore permits, in Java

Can I add more permit to a semaphore in Java?

Semaphore s = new Semaphore(3);

After this somewhere in the code i want to change the permits to 4. Is this possible?

Yes. The release method (confusingly named imo) can be used to increment permits since, from the docs:

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. 

In other words:

semaphore.release(10);

Will add 10 more permits if the thread calling hasn't acquired any.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM