Difference between Semaphore and Condition (ReentrantLock)

瘦欲@ 提交于 2020-01-21 03:52:44

问题


Does anyone know the differences between the methods acquire () and release () (java.util.concurrent.Semaphore) and await () and signal (new ReentrantLock().newCondition() ) .

Can you expose a pseudo code for each of these methods?


回答1:


Superficially the behavior of these method might look similar - acquire()/await() can make threads block in some cirsumstances and release()/signal() can unblock threads in some circumstances. However Semaphore and Condition serve different purposes:

  • java.util.concurrent.Semaphore is relatively higher-level synchronization mechanism, intended for use by general developers. You would use it typically to restrict concurrent access to some resource by making each requester thread call acquire() before accessing the resource (that way making the thread block if no semaphore permit was available). Description from the javadoc:

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

  • java.util.concurrent.locks.Condition is relatively low-level synchronization mechanism which basically enhances functionality provided java.lang.Object methods wait(), notify() and notifyAll(). It enables the thread to suspend its activities when it needs to wait for some condition to become true (generally through activity of other threads) and then it enables those other threads to "wake up" the waiting thread(s) when the state variables taking part in the condition might have changed. It is generally harder to use correctly and general developers are advised to use higher-level mechanisms from package java.util.concurrent (like Semaphore).

You can find more detailed information about this in the excellent book "Java Concurrency in Practice" from Brian Goetz.



来源:https://stackoverflow.com/questions/12641933/difference-between-semaphore-and-condition-reentrantlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!