简体   繁体   English

信号量和条件之间的区别(ReentrantLock)

[英]Difference between Semaphore and Condition (ReentrantLock)

Does anyone know the differences between the methods acquire () and release () ( java.util.concurrent.Semaphore ) and await () and signal (new ReentrantLock().newCondition() ) . 有谁知道方法acquire ()release ()java.util.concurrent.Semaphore )和await ()signal (new ReentrantLock().newCondition() )之间的区别。

Can you expose a pseudo code for each of these methods? 你能为这些方法公开一个伪代码吗?

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. 从表面上看,这些方法的行为可能看起来类似 - acquire()/await()可以使线程在某些情况下阻塞,而release()/signal()可以在某些情况下解除阻塞。 However Semaphore and Condition serve different purposes: 但是,信号量和条件有不同的用途:

  • java.util.concurrent.Semaphore is relatively higher-level synchronization mechanism, intended for use by general developers. java.util.concurrent.Semaphore是相对较高级别的同步机制,供一般开发人员使用。 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). 您通常会使用它来限制对某些资源的并发访问,方法是在访问资源之前让每个请求者线程调用acquire() (如果没有可用的信号量许可,就会产生线程阻塞)。 Description from the javadoc: 来自javadoc的描述:

    Conceptually, a semaphore maintains a set of permits. 从概念上讲,信号量保持一组许可。 Each acquire() blocks if necessary until a permit is available, and then takes it. 如果需要,每个acquire()都会阻止,直到有许可证可用,然后接受它。 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() . java.util.concurrent.locks.Condition是相对低级的同步机制,它基本上增强了java.lang.Object方法wait()notify()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). 通常更难正确使用,建议一般开发人员使用java.util.concurrent包中的更高级别的机制(如Semaphore)。

You can find more detailed information about this in the excellent book "Java Concurrency in Practice" from Brian Goetz. 您可以在Brian Goetz的优秀书籍“Java Concurrency in Practice”中找到有关此内容的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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