乐趣区

关于java:ReadWriteLock

ReadWriteLock 读写锁,只有读读不互斥,其余都互斥。写了个小 demo,来加深下印象。
public class MyChahe {private Map<String,Object> map=new HashMap<>();

    private ReadWriteLock lock=new ReentrantReadWriteLock();

    public void put(String key,Object value){
        try{lock.writeLock().lock();
            System.out.println("当初开始进行 put 操作 ----------");
            map.put(key,value);
            Thread.sleep(5000);
            System.out.println("put 操作完结 ----------");
        }catch (Exception e){e.printStackTrace();
        }finally{lock.writeLock().unlock();}
    }

    public void get(String key){
        try{lock.readLock().lock();
            System.out.println("当初开始进行 get 操作 ----------");
            Object value = map.get(key);
            System.out.println("get 操作完结 ----------,value-->"+value);
        }catch (Exception e){e.printStackTrace();
        }finally{lock.readLock().unlock();}
    }
}
public class LockTest {public static void main(String[] args) throws InterruptedException {MyChahe cache=new MyChahe();
        new Thread(()->{cache.put("1","aaaaaaaaaa");
        }).start();

        Thread.sleep(300);

        new Thread(()->{cache.get("1");
        }).start();}
}

当有线程获取写锁的时候,其余线程去调用读相干操作,没方法获取读锁,只能期待写锁开释,才能够获取。

退出移动版