Java--JUC--ReetrantReadLock读写锁

  1.  ReadWriteLock 使用
  2.   ReadWriteLock readWriteLock =new ReentrantReadWriteLock()
  3.   
    package com.model.new_concurrent;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReadWriteLock;
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    /**
     * @Description:测试类
     * @Author: 张紫韩
     * @Crete 2021/6/6 21:27
     */
    public class Test02 {
        public static void main(String[] args) {
            MapTest mapTest=new MapTest();for (int i = 1; i <=5; i++) {
                int temp= i;
                new Thread(() ->{
                    mapTest.set(temp+"",temp+"");
                },"A").start();
            }
            for (int i = 1; i <=5; i++) {
                int temp= i;
                new Thread(() ->{
                    mapTest.get(temp+"");
                },"A").start();
            }
    
        }
    
    }
    class MapTest{
        private  volatile  Map<String,Object>  map=new HashMap<>();
        private ReadWriteLock readWriteLock= new ReentrantReadWriteLock();
        public void set(String k,String v){
            readWriteLock.writeLock().lock();
            try {
                System.out.println("写入"+k);
                TimeUnit.SECONDS.sleep(2);
                map.put(k,v);
                System.out.println("完成"+k);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                readWriteLock.writeLock().unlock();
            }
    
        }
    
        public void get(String k){
            readWriteLock.readLock().lock();
            try {
                System.out.println("读取"+k);
                TimeUnit.SECONDS.sleep(2);
                map.get(k);
                System.out.println("完成"+k);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                readWriteLock.readLock().unlock();
            }
        }
    
    }

     

      

 

posted @ 2021-06-06 22:33  张紫韩  阅读(41)  评论(0编辑  收藏  举报