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

标签 java multithreading

我正在阅读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/

相关文章:

java - 尝试运行Spring Boot应用程序时无法部署到Docker

JAVA和JODA Date解析即使格式错误也不会抛出异常

java - 比较 c#、c++ 和 java 性能(c# 的奇怪行为)

multithreading - 如何同时运行5个Shell作业并在Queue中保持休息?

c# - 您希望设计架构具备哪些品质,以便编码团队可以轻松实现?

java - 组播错误: Multicast Address Not Found

java - OutputStream.write 仅在 Java 中写入字符串的一部分

c# - 检测不可变对象(immutable对象)的高效方法?

ruby-on-rails - Rails 创建新线程或后台进程

java - 混合模式下的 jstack : WrongTypeException: No suitable match for type of address