zoukankan      html  css  js  c++  java
  • 读写锁

    读写锁

    ReentrantReadWriteLock

    读,可多线程读

    写,只允许一个写

    • 读读共存

    • 读写不共存

    • 写写不共存

    写操作:原子+独占,整个过程必须是一个完整的统一体,中间不需被分割打断

    // 资源类
    class Mycache{
        // 缓存的一般加volatile
        private volatile Map<String,Object> map = new HashMap<>();
        //private Lock lock = new ReentrantLock();
        private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        
        //
        public void put(String key,Object value){
            //System.out.println(Thread.currentThread.getName()+"写入中");
            //TimeUnit.MILLISECONDS.sleep(300);
            //map.put(key,value);
            //System.out.println(Thread.currentThread.getName()+"写入完成");
            rwLock.writeLock().lock();
            try{
                map.put(key,value);
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                rwLock.writeLock().unlock();
            }
            
        }
        //
        public Object get(String key){
           // System.out.println(Thread.currentThread.getName()+"读取中");
           // TimeUnit.MILLISECONDS.sleep(300);
           // Object result = map.get(key);
           // System.out.println(Thread.currentThread.getName()+"读取完成");
            rwLock.readLock().lock();
            try{
                return map.get(key);
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                rwLock.readLock().unlock();
            }
            
        }
    }
    
    public class ReadWriteLockTest{
        public static void main(String[] args){
            Mycache mycache = new Mycache();
            // 五个线程写
            for(int i=0; i<5; i++){
                final int tempInt = i;
                new Thread(()->{
                    mycache.put(tempInt+"",tempInt+"");
                },String.valueOf(i)).start();
            }
            // 五个线程读
            for(int i=0; i<5; i++){
                final int tempInt = i;
                new Thread(()->{
                    mycache.get(tempInt+"");
                },String.valueOf(i)).start();
            }
        }
    }

    结果显示:写锁会独占写,读锁则是共享读

     

  • 相关阅读:
    c++中的复合类型
    c++获取随机数
    静态成员数据和静态成员函数
    c++之window.h
    算法之美---100幅由程序生成的图像,总有一幅让你感到惊艳[上]
    分形的程序实现
    使用异或运算交换两个任意类型变量
    游戏中角色曲线行走的算法
    算法之美---由计算机生成的图像
    数学图形之肾形
  • 原文地址:https://www.cnblogs.com/wsZzz1997/p/14673478.html
Copyright © 2011-2022 走看看