信号量和条件之间的差异(ReentrantLock) [英] Difference between Semaphore and Condition (ReentrantLock)

查看:351
本文介绍了信号量和条件之间的差异(ReentrantLock)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道方法 acquire() release()之间的区别 java.util.concurrent.Semaphore )和 await() signal(new ReentrantLock()。newCondition )

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?

推荐答案

表面上这些方法的行为可能看起来类似 - acquire()/ await()可以使线程阻塞在一些情况和 release signal()可以在某些情况下解除锁定线程。但是,信号量和条件具有不同的用途:

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 是相对较高级别的同步机制,供一般开发人员使用。通常,通过在访问资源之前使每个请求者线程调用 acquire()来限制对某些资源的并发访问(如果没有信号量许可证可用)。
    javadoc中的描述:

  • 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:


概念上,信号量维护一组许可。每个获取()块,如果有必要,直到许可证可用,然后采取它。每个release()都添加了一个许可,可能会释放一个阻止获取方。

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 是相对较低级别的同步机制,它基本上增强了 java.lang.Object 方法等待() notify() notifyAll()。它使线程能够在需要等待某些条件变为真时(通常通过其他线程的活动)挂起其活动,然后当状态变量采用时,它使那些其他线程唤醒等待的线程部分条件可能已更改。通常更难正确使用,一般开发人员建议使用java.util.concurrent包(如Semaphore)中的更高级别的机制。

  • 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).

    您可以在Brian Goetz的优秀的Java Concurrency in Practice一书中找到更详细的信息。

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

    这篇关于信号量和条件之间的差异(ReentrantLock)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆