展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

锁(六):AQS使用单一int值表示读写两种状态

  • 查看源码
# ctrl + 点击ReentrantReadWriteLock
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 6317671515068378041L;
/*
* Read vs write count extraction constants and functions.
* Lock state is logically divided into two unsigned shorts:
* The lower one representing the exclusive (writer) lock hold count,
* and the upper the shared (reader) hold count.
*/
static final int SHARED_SHIFT = 16;
static final int SHARED_UNIT = (1 << SHARED_SHIFT);
static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
/** Returns the number of shared holds represented in count. */
static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
/** Returns the number of exclusive holds represented in count. */
static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
  • 步骤
int32位,将其拆分成两个无符号short
高位表示读锁 低位表示写锁
0000000000000000 0000000000000000
两种锁的最大次数均为65535也即是216次方减去1
读锁二进制表示:每次都从当前的状态加上65536
0000000000000000 0000000000000000 // 初始值
0000000000000001 0000000000000000 // 65536的二进制表示
-----------------------------------
0000000000000001 0000000000000000 // 获取读锁个数,将state整个无符号右移16位就可得出读锁的个数
0000000000000001 // 读锁个数
-----------------------------------
写锁:每次都直接加1
0000000000000000 0000000000000000 // 初始值
0000000000000000 0000000000000001 // 写锁表示方式
-----------------------------------
0000000000000000 0000000000000001 // 与运算
0000000000000000 1111111111111111 // 写锁的个数
posted @   DogLeftover  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示