维护了一对锁,read lock 可以由多个线程执行,只要没有作者那么write lock就是独家的
package com.jie.rw; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockDemo { public static void main(String[] args) { MyCache myCache=new MyCache(); //写入 for (int i = 1; i <= 5; i++) { final int temp=i; new Thread(()->{ myCache.put(temp+"",temp+""); },String.valueOf(i)).start(); } //读取 for (int i = 1; i <= 5; i++) { final int temp=i; new Thread(()->{ myCache.get(temp+""); },String.valueOf(i)).start(); } } } class MyCache{ private volatile Map<String,Object> map=new HashMap<>(); //读写锁 ReentrantReadWriteLock lock= new ReentrantReadWriteLock(); //模拟写 public void put(String key,Object value){ lock.writeLock().lock(); try{ System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key,value); System.out.println(Thread.currentThread().getName()+"写入完毕"); } catch (Exception e){ e.printStackTrace(); } finally { lock.writeLock().unlock(); } } //模拟读 public void get(String key){ lock.readLock().lock(); try{ System.out.println(Thread.currentThread().getName()+"读取"+key); Object o=map.get(key); System.out.println(Thread.currentThread().getName()+"读取完毕"); } catch (Exception e){ e.printStackTrace(); } finally { lock.readLock().unlock(); } } }
运行可以看到写入是一个一个写完 但是读取可以插队