等待……通知低级同步的最佳选择是什么? [英] What's the best alternative to wait...notify for low level synchronization?

查看:19
本文介绍了等待……通知低级同步的最佳选择是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,wait()notify() 已经被更好的并发机制所取代.那么,你会选择什么更好的替代方案,比如实现 同步队列?

As far as I know, wait() and notify() have been replaced with better concurrency mechanisms. So, what better alternative would you choose, say for implementing a synchronized queue?

他们究竟在什么意义上更好"?

In what sense exactly are they "better"?

编辑:这是一道面试题(实现同步队列").可接受的答案不能使用 BlockingQueue 或其他队列实现.但是,它可能会使用其他同步构造,例如 CountDownLatch.我没有详尽的允许和禁止课程列表 - 用你的头脑.

Edit: This ("implement a synchronous queue") is an interview question. An acceptable answer cannot use BlockingQueue or other queue implementation. It might, however, use other synchronization constructs such as CountDownLatch. I do not have an exhaustive list of allowed and forbidden classes - use your heads.

推荐答案

synchronized/wait()/notify()/notifyAll() 已直接替换为 Lock 类方法 lock()/unlock()/newCondition() 和 Condition 的 await()/signal()/signalAll().

synchronized/wait()/notify()/notifyAll() have been directly replaced by the Lock class methods lock()/unlock()/newCondition() and Condition's await()/signal()/signalAll().

这些有几个好处,首先允许额外的语义,如公平策略,以及分布式锁定等功能.对多个 Condition 对象的支持允许更细粒度的信号以及不间断的等待和等待一段时间等.

There are several benefits to these, for a start allowing additional semantics such as fairness policies, as well as features such as distributed locking. The support for multiple Condition objects allows for much finer-grained signalling as well as uninterruptible waiting and waiting until some time etc.

例如,链接的代码有单独的对象,它试图用于发出信号(由于等待时相关监视器没有被保持,这将失败).这可以通过使用具有多个条件的单个 Lock 直接替换.

For instance, the linked code has separate objects it attempts to use for signalling (which will fail due to the fact that the relevant monitors aren't held when waiting). This is directly replaceable by the use of a single Lock with multiple conditions.

在改进方面,附加功能可能是有价值的.在 Java5 中,显式 Lock 实现实际上比 JVM 监视器表现得更好,但它们基本上削弱了 Doug Lea 的 JVM 代码,现在性能大致相当.

In terms of improvements, the additional functionality may be of value. In Java5 the explicit Lock implementations actually performed better than the JVM monitors, but they basically nicked Doug Lea's code for the JVM and performance is now roughly equivalent.

这篇关于等待……通知低级同步的最佳选择是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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