gpt4 book ai didi

java - 为什么支持共享获取的同步器是独占获取的?

转载 作者:行者123 更新时间:2023-11-30 05:19:06 25 4
gpt4 key购买 nike

我正在阅读Java并发实践,在“14.5 AbstractQueuedSynchronizer”中,它说:

A synchronizer supporting exclusive acquisition should implement the protected methods tryAcquire, tryRelease, and isHeldExclusively, and those supporting shared acquisition should implement tryAcquireShared and tryReleaseShared. The acquire, acquireShared, release, and releaseShared methods in AQS call the try forms of these methods in the synchronizer subclass to determine if the operation can proceed. The synchronizer subclass can use getState, setState, and compareAndSetState to examine and update the state according to its acquire and release 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 from tryAcquireShared indicates acquisition failure; returning zero indicates the synchronizer was acquired exclusively; and returning a positive value indicates the synchronizer was acquired nonexclusively. The tryRelease and tryReleaseShared methods should return true if the release may have unblocked threads attempting to acquire the synchronizer.

我不太明白那两个粗体句子。

  • 支持共享获取的同步器应实现tryAcquireSharedtryReleaseShared
  • 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/

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