JUC个人学习笔记7-读写锁
根据b站UP主狂神说JUC课程所写的个人学习笔记
视频地址:https://www.bilibili.com/video/BV1B7411L7tE?from=search&seid=14761503393031794075
ReadWriteLock
读的时候可以多线程读,写的时候只能一个写
//独占锁(写锁) //共享锁(读锁) //1.读-读 可以共存2.读-写 不能共存3.写-写 不能共存 public class ReadWriteLockDemo { public static void main(String[] args) { MyCacheLock myCache = new MyCacheLock(); //写入 for (int i = 0; i < 5; i++) { final int temp = i; new Thread(()->{ myCache.put(temp+"",temp+""); },String.valueOf(i)).start(); } //读取 for (int i = 0; i < 5; i++) { final int temp = i; new Thread(()->{ myCache.get(temp+""); },String.valueOf(i)).start(); } } } //加锁的 class MyCacheLock{ private volatile Map<String,Object> map = new HashMap<>(); //读写锁,更加细粒度的控制 private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(); //写入的时候只希望一个线程写 public void put(String key,Object value){ reentrantReadWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key,value); System.out.println(Thread.currentThread().getName()+"写入ok"+key); } catch (Exception e) { e.printStackTrace(); }finally { reentrantReadWriteLock.writeLock().unlock(); } } //读的时候可以多线程读 public void get(String key){ //取 reentrantReadWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取ok"+key); } catch (Exception e) { e.printStackTrace(); }finally { reentrantReadWriteLock.readLock().unlock(); } } } class MyCache{ private volatile Map<String,Object> map = new HashMap<>(); public void put(String key,Object value){ System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key,value); //存 System.out.println(Thread.currentThread().getName()+"写入ok"+key); } public void get(String key){ //取 System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取"+key); } }