读写锁(独占锁,共享锁)-手写缓存
package com.demo.lock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class MyCache //资源类 { //手动实现缓存基本都要 volatile 修饰 private volatile Map<String,Object> map=new HashMap<>(); private ReentrantReadWriteLock rwLock=new ReentrantReadWriteLock(); public void put(String key,Object value){ rwLock.writeLock().lock();//独占锁 System.out.println(Thread.currentThread().getName()+"正在写入……"); try { TimeUnit.MILLISECONDS.sleep(300); map.put(key,value); System.out.println(Thread.currentThread().getName()+"写入完成*****"); } catch (InterruptedException e) { e.printStackTrace(); }finally { rwLock.writeLock().unlock(); } } public void get(String key){ rwLock.readLock().lock();//共享锁 System.out.println(Thread.currentThread().getName()+"正在读取……"); try { TimeUnit.MILLISECONDS.sleep(300); Object value = map.get(key); System.out.println(Thread.currentThread().getName()+"读取完毕:"+value); } catch (InterruptedException e) { e.printStackTrace(); }finally { rwLock.readLock().unlock(); } } } public class ShareLock { public static void main(String[] args) { MyCache myCache=new MyCache(); for (int i = 1; i <5 ; i++) { final int tempInt=i; new Thread(()->{ myCache.put(tempInt+"",tempInt+""); },String.valueOf(i)).start(); } for (int i = 1; i <5 ; i++) { final int tempInt=i; new Thread(()->{ myCache.get(tempInt+""); },String.valueOf(i)).start(); } } }