我正在阅读Java并发实践,在“14.5 AbstractQueuedSynchronizer”中,它说:
A synchronizer supporting exclusive acquisition should implement the protected methods
tryAcquire
,tryRelease
, andisHeldExclusively
, and those supporting shared acquisition should implementtryAcquireShared
andtryReleaseShared
. Theacquire
,acquireShared
,release
, andreleaseShared
methods in AQS call thetry
forms of these methods in the synchronizer subclass to determine if the operation can proceed. The synchronizer subclass can usegetState
,setState
, andcompareAndSetState
to examine and update the state according to itsacquire
andrelease
semantics, and informs the base class through the return status whether the attempt to acquire or release the synchronizer was successful. For example, returning a negative value fromtryAcquireShared
indicates acquisition failure; returning zero indicates the synchronizer was acquired exclusively; and returning a positive value indicates the synchronizer was acquired nonexclusively. ThetryRelease
andtryReleaseShared
methods should return true if the release may have unblocked threads attempting to acquire the synchronizer.
我不太明白那两个粗体句子。
- 支持共享获取的同步器应实现
tryAcquireShared
和tryReleaseShared
。 - 从
tryAcquireShared
返回零表示同步器是独占获取的。
为什么支持共享获取的同步器是独占获取的?
最佳答案
Synchronizer 可能支持独占和共享获取 - 在这种情况下,从 tryAcquireShared 返回 0 是有意义的。根据 AbstractQueuedSynchronizer
文档:
Usually, implementation subclasses support only one of these modes, but both can come into play for example in a ReadWriteLock. Subclasses that support only exclusive or only shared modes need not define the methods supporting the unused mode.
关于java - 为什么支持共享获取的同步器是独占获取的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59833209/