gpt4 book ai didi

java - 条件 vs 等待通知机制

转载 作者:IT老高 更新时间:2023-10-28 13:52:51 24 4
gpt4 key购买 nike

与传统的等待通知机制相比,使用 Condition 接口(interface)/实现有什么优势?这里我引用 Doug Lea 写的评论:

Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.

我看到这是一种更面向对象的实现等待/通知机制的方式。但与前者相比有明显优势吗?

最佳答案

最大的问题是等待/通知对于新开发人员来说很容易出错。主要问题是不知道如何正确处理它们可能导致晦涩的错误。

  • 如果你在 wait() 之前调用 notify(),它就会丢失。
  • 有时可能不清楚 notify() 和 wait() 是否在同一个对象上调用。
  • wait/notify 中没有需要更改状态的内容,但在大多数情况下这是必需的。
  • wait() 可以虚假返回

Condition 将此功能封装到一个专用组件中,但其行为大致相同。

有一个关于等待/nofity 在此之前几分钟发布的问题,还有更多 Search [java]+wait+notify

关于java - 条件 vs 等待通知机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10395571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com