ReentrantReadWriteLock模拟JVM本地缓存案例

一、案例代码

public class ReadLockAndWriteLockTest {
    //存储数据
    private volatile Map<String,String> map=new HashMap<>();
    //读写锁
    private ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    //写入锁
    private WriteLock writeLock=readWriteLock.writeLock();
    //读取锁
    private ReadLock readLock=readWriteLock.readLock();

    //添加元素
    public void put(String key,String value){
        try {
            writeLock.lock();
            System.out.println("写入开始数据开始,key:"+key+",value:"+value);
            map.put(key,value);
            System.out.println("写入开始数据结束,key:"+key+",value:"+value);
        } finally {
            writeLock.unlock();
        }
    }

    //读取元素
    public  String get(String key){
        try {
            readLock.lock();
            System.out.println("读数据开始,key:"+key);
            String value = map.get(key);
            System.out.println("读数据开始,key:"+key+",value:"+value);
            return  value;
        } catch (Exception e) {
            return null;
        } finally {
           readLock.unlock();
        }
    }

    public static void main(String[] args) {
        ReadLockAndWriteLockTest readLockAndWriteLockTest=new ReadLockAndWriteLockTest();
        //写线程
        Thread writeThread=new Thread(()->{
            for (int i = 0; i < 10; i++) {
                readLockAndWriteLockTest.put(i+"",i+"");
            }
        });
        writeThread.start();
        //读线程
        Thread readThread=new Thread(()->{
            for (int i = 0; i < 10; i++) {
                readLockAndWriteLockTest.get(i+"");
            }
        });
        readThread.start();
    }

}

二、测试结果

未加锁时:

加读写锁以后:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值