gpt4 book ai didi

java - 如何实现独写,非独读?

转载 作者:搜寻专家 更新时间:2023-10-31 19:56:21 25 4
gpt4 key购买 nike

如何实现独占写,非独占读?我可以同步 对 setter 的访问并使变量 volatile 吗?够了吗?

最佳答案

看Java5并发api:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html

这将实现您的要求,因为您可以允许多个线程读取而不锁定并且仅在写入时锁定。

这是一篇有趣的文章,在阅读时将此 api 与传统的同步进行了比较:ReentrantReadWriteLock vs synchronized

此外,正如@assylias 在评论中所说,您应该避免在非必要时进行锁定。

事实上,只有当两个条件都满足时,您才可以信任 volatile 关键字:

You can use volatile variables instead of locks only under arestricted set of circumstances. Both of the following criteria mustbe met for volatile variables to provide the desired thread-safety:

_ Writes to the variable do not depend on its current value.

_ Thevariable does not participate in invariants with other variables.

关于java - 如何实现独写,非独读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15728858/

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