ReadWriteLock

ReadWriteLock

翻译:

读取写入锁

解释:

  • 在写入与读取的时候,会被其他线程插队,对于读取线程是不要紧的,但是对于读取线程,就会出现很多的问题

  • 在以前我们可以synchronized ,ReetrentLock锁住

  • 现在使用更加细腻的 ReadWriteLock

用法

不加锁的情况下

public class ReadAndWriteLockTest {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() ->{
                myCache.pushItem(String.valueOf(finalI), finalI);
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() ->{
                myCache.getItem(String.valueOf(finalI));
            },String.valueOf(i)).start();
        }

    }

}
class MyCache{
    private Map<String ,Integer> map = new HashMap<>();

    public void pushItem(String key,Integer value){
        System.out.println(Thread.currentThread().getName() + "准备写入");
        map.put(key,value);
        System.out.println(Thread.currentThread().getName() + "写入成功");
    }

    public void getItem(String key){
        System.out.println(Thread.currentThread().getName() + "准备读取");
        map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取成功");
    }
}
  • 会出现写入的时候,其他线程插队的情况

加入读写锁ReadWriteLock

class MyCache{

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Map<String ,Integer> map = new HashMap<>();

    public void pushItem(String key,Integer value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "准备写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName() + "写入成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void getItem(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "准备读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
  • ReadWriteLock是接口,实现类是 ReetrantReadWirteLock,所以接口与实现类啦
  • 通过上述的内容,就可以实现了在写入的时候,没有新的线程的插队
  • 但是为什么是所有的 写入数据 先执行,这是我所不知道的
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值