gpt4 book ai didi

java - 读写RentrantLock

转载 作者:行者123 更新时间:2023-12-01 14:43:20 24 4
gpt4 key购买 nike

我对RentrantReadWriteLock的理解其特点是它允许同时进行多次读取,但只允许一次写入。

当我们尝试获取读锁时 doc

Acquires the read lock if the write lock is not held by another thread and returns immediately.

If the write lock is held by another thread then the current thread becomes disabled
for thread scheduling purposes and lies dormant until the read lock has been acquired.

这里的held是什么意思?

  • 另一个线程请求了写锁并执行了 write 操作?

  • 上述情况以及另一个线程请求写锁但正在等待获取它的情况。

因为当请求写锁时,如果满足以下条件,则不会授予它:

  • 其他人有写锁
  • 其他人有读锁

来自write lock文档:

Acquires the write lock if neither the read nor write lock are held by another 
thread and returns immediately, setting the write lock hold count to one.

...

If the lock is held by another thread then the current thread becomes
disabled for thread scheduling purposes and lies dormant until the write lock has
been acquired, at which time the write lock hold count is set to one.

因此,当线程在请求​​写入锁后等待写入锁时,我只想了解读取锁调用的后续行为。他们是否会让写锁请求等待更长时间?

最佳答案

在此上下文中

持有表示已请求并提供锁定。如果您只是在等待,则不会被视为持有

当大量线程请求锁定时,ReentrantReadWriteLock 存在已知问题。 Heinz Kabutz 博士制作了一个有趣的 newsletter与他们一起锁饥饿。

据我了解,新的 Java 7 Phaser 已修复其中许多问题。但我还不太熟悉它,无法说是哪种方式。

关于java - 读写RentrantLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721129/

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