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

    代码:

    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    //写,原子独占
    class MyCache {
        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){
            rwLock.writeLock().lock();
            try {
                System.out.println(Thread.currentThread().getName()+"	 正在写入:"+key);
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                map.put(key,value);
                System.out.println(Thread.currentThread().getName()+"	 写入:"+key);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                rwLock.writeLock().unlock();
            }
        }
    
        public void get(String key){
            rwLock.readLock().lock();
            try {
                System.out.println(Thread.currentThread().getName()+"	 正在读取:"+key);
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                Object result=map.get(key);
                System.out.println(Thread.currentThread().getName()+"	 读取完成:"+result);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                rwLock.readLock().unlock();
            }
        }
    }
    public class ReadWriteLockDemo {
        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=1;i<=5;i++){
                final int tempInt=i;
                new Thread(()->{
                    myCache.get(tempInt+"");
                },String.valueOf(i)).start();
            }
        }
    }
    

      

  • 相关阅读:
    PAT-乙级-1011. A+B和C (15)
    PAT-乙级-1010. 一元多项式求导 (25)
    PAT-乙级-1009. *说反话 (20)
    PAT-乙级-1008. 数组元素循环右移问题 (20)
    PAT-乙级-1007. 素数对猜想 (20)
    PAT-乙级-1006. 换个格式输出整数 (15)
    PAT-乙级-1005. 继续(3n+1)猜想 (25)
    PAT-乙级-1004. 成绩排名 (20)
    BZOJ 1030: [JSOI2007]文本生成器
    BZOJ 2938: [Poi2000]病毒
  • 原文地址:https://www.cnblogs.com/sunliyuan/p/12500702.html
Copyright © 2011-2022 走看看