展开
拓展 关闭
订阅号推广码
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; }

  • 步骤
int 是32位,将其拆分成两个无符号short 
高位表示读锁      低位表示写锁 
0000000000000000 0000000000000000 

两种锁的最大次数均为65535也即是2的16次方减去1 

读锁二进制表示:每次都从当前的状态加上65536 
0000000000000000 0000000000000000         // 初始值
0000000000000001 0000000000000000         // 65536的二进制表示
----------------------------------- 
0000000000000001 0000000000000000         // 获取读锁个数,将state整个无符号右移16位就可得出读锁的个数 
                 0000000000000001         // 读锁个数
----------------------------------- 
写锁:每次都直接加1 
0000000000000000 0000000000000000         // 初始值
0000000000000000 0000000000000001         // 写锁表示方式
----------------------------------- 
0000000000000000 0000000000000001         // 与运算
0000000000000000 1111111111111111         // 写锁的个数 
posted @ 2022-05-14 14:34  DogLeftover  阅读(19)  评论(0编辑  收藏  举报