十五、ReadWriteLock读写锁

  1. 读写锁。

    串行写入,并行读取。

  2. 示例

    public class ReadWriteLockTest {
        public static void main(String[] args) {
            MyCacheLock myCacheLock = new MyCacheLock();
    
            //5条线程写
            for (int i = 1; i <= 5; i++) {
                final int tp = i;
                new Thread(()->{
                    myCacheLock.setCache(tp+"",tp+"");
                },String.valueOf(i)).start();
            }
    
            //5条线程读
            for (int i = 1; i <= 5; i++) {
                final int tp = i;
                new Thread(()->{
                    myCacheLock.getCache(tp+"");
                },String.valueOf(i)).start();
            }
        }
    }
    
    /**
     * 缓存类
     */
    class MyCacheLock{
    
        //volatile 保证可见性
        private volatile Map<String,Object> map = new HashMap<>();
        private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    
        /**
         * 写入缓存
         * @param key
         * @param val
         */
        public void setCache(String key,Object val){
            readWriteLock.writeLock().lock();
            try{
                System.out.println("线程"+Thread.currentThread().getName()+"开始写入:" + key);
                map.put(key,val);
                System.out.println("线程"+Thread.currentThread().getName()+"写入:" + key + "完成");
            }
            finally {
                readWriteLock.writeLock().unlock();
            }
        }
    
        /**
         * 读取缓存
         * @param key
         * @return
         */
        public Object getCache(String key){
            readWriteLock.readLock().lock();
            try{
                System.out.println("线程"+Thread.currentThread().getName()+"开始读取:" + key);
                Object res = map.get(key);
                System.out.println("线程"+Thread.currentThread().getName()+"读取:" + key + "完成");
                return res;
            }
            finally {
                readWriteLock.readLock().unlock();
            }
        }
    }
    

    打印结果

    线程1开始写入:1
    线程1写入:1完成
    线程2开始写入:2
    线程2写入:2完成
    线程3开始写入:3
    线程3写入:3完成
    线程4开始写入:4
    线程4写入:4完成
    线程5开始写入:5
    线程5写入:5完成
    线程3开始读取:3
    线程3读取:3完成
    线程4开始读取:4
    线程1开始读取:1
    线程1读取:1完成
    线程2开始读取:2
    线程2读取:2完成
    线程5开始读取:5
    线程4读取:4完成
    线程5读取:5完成
    

    从上面结果可以看出,写入线程在写操作时,从写入开始到写入完成,中间是不会插入其他内容的。因为写锁是独占的,具有排他性。此时其他的写线程和所有读线程都会等待。

    读取线程在开始读取和读取完成之间插入有其他内容。是因为读锁是共享的,其他读线程可以共同进入,而写线程需要等待。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值