package com.shangguigu; 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; public class ReadWritelockDemo { public static void main(String[] args) { MyCache myCache = new MyCache(); 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 MyCache{ private volatile Map<String,Object> map = new HashMap(); ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public void put(String key,Object value){ readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"写入数据"+key); //暂停一会线程 try { TimeUnit.MICROSECONDS.sleep(300); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } map.put(key, value); System.out.println(Thread.currentThread().getName()+"写入数据完成"); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { // TODO: handle finally clause readWriteLock.writeLock().unlock(); } } public void get(String key){ readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+"读取数据"+key); //暂停一会线程 try { TimeUnit.MICROSECONDS.sleep(300); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } Object result = map.get(key); System.out.println(Thread.currentThread().getName()+"读取数据完成"+result); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { // TODO: handle finally clause readWriteLock.readLock().unlock(); } } }
执行结果:
0写入数据0
0写入数据完成
1写入数据1
1写入数据完成
2写入数据2
2写入数据完成
3写入数据3
3写入数据完成
4写入数据4
4写入数据完成
1读取数据1
2读取数据2
0读取数据0
3读取数据3
4读取数据4
3读取数据完成3
1读取数据完成1
0读取数据完成0
4读取数据完成4
2读取数据完成2