读写锁
ReentrantReadWriteLock
读,可多线程读
写,只允许一个写
-
读读共存
-
读写不共存
-
写写不共存
写操作:原子+独占,整个过程必须是一个完整的统一体,中间不需被分割打断
// 资源类 class Mycache{ // 缓存的一般加volatile private volatile Map<String,Object> map = new HashMap<>(); //private Lock lock = new ReentrantLock(); private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); // 写 public void put(String key,Object value){ //System.out.println(Thread.currentThread.getName()+"写入中"); //TimeUnit.MILLISECONDS.sleep(300); //map.put(key,value); //System.out.println(Thread.currentThread.getName()+"写入完成"); rwLock.writeLock().lock(); try{ map.put(key,value); }catch (Exception e){ e.printStackTrace(); }finally{ rwLock.writeLock().unlock(); } } // 读 public Object get(String key){ // System.out.println(Thread.currentThread.getName()+"读取中"); // TimeUnit.MILLISECONDS.sleep(300); // Object result = map.get(key); // System.out.println(Thread.currentThread.getName()+"读取完成"); rwLock.readLock().lock(); try{ return map.get(key); }catch (Exception e){ e.printStackTrace(); }finally{ rwLock.readLock().unlock(); } } } public class ReadWriteLockTest{ public static void main(String[] args){ Mycache mycache = new Mycache(); // 五个线程写 for(int i=0; i<5; i++){ final int tempInt = i; new Thread(()->{ mycache.put(tempInt+"",tempInt+""); },String.valueOf(i)).start(); } // 五个线程读 for(int i=0; i<5; i++){ final int tempInt = i; new Thread(()->{ mycache.get(tempInt+""); },String.valueOf(i)).start(); } } }
结果显示:写锁会独占写,读锁则是共享读