6.读写锁
/** * @author wuyimin * @create 2021-07-08-20:12 * @description 允许同时读,不允许同时写或者同时写和读 */ public class ReadWriteLockDemo { public static void main(String[] args) { MyCache cache = new MyCache(); //写入操作 for (int i = 0; i < 5; i++) { final int temp=i; new Thread(()->{ cache.put(temp+"",temp); },String.valueOf(i)).start(); } //读取操作 for (int i = 0; i < 5; i++) { final int temp=i; new Thread(()->{ cache.get(temp+""); },String.valueOf(i)).start(); } } } /* 自定义缓存 */ class MyCache{ private volatile Map<String,Object> map=new HashMap<>(); //读写锁 private ReentrantReadWriteLock lock=new ReentrantReadWriteLock(); //存,写 public void put(String key,Object value){ lock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"开始写"); 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()+"开始读"); Object o=map.get(key); System.out.println(Thread.currentThread().getName()+"完成读"); } catch (Exception e) { e.printStackTrace(); }finally { lock.readLock().unlock(); } } }