/** * 读写锁 */ public class ReadWriteLockDemo { public static void main(String[] args) { // MyCache myCache = new MyCache(); MyCacheLock myCache = new MyCacheLock(); for (int i =1;i<=5;i++){ final int temp = i; new Thread(()->{ myCache.put(temp+"",temp); }).start(); } for (int i =1;i<=5;i++){ final int temp = i; new Thread(()->{ myCache.get(temp+""); }).start(); } } } class MyCacheLock { private volatile Map<String, Object> map = new HashMap<>(); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();//读写锁 //写入,每次只能有一个线程进入 public void put(String key, Object value) { try { readWriteLock.writeLock().lock(); System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key, value); System.out.println(Thread.currentThread().getName()+"写入成功"+key); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } //读取,每次可以多个线程读取 public void get(String key) { try { readWriteLock.readLock().lock(); System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取成功"+key); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.readLock().unlock(); } } }
读写锁(ReadWriteLock)
最新推荐文章于 2024-09-28 11:05:11 发布