Java中的读写锁 ReentrantReadWriteLock
Posted on 2020-04-13 17:31 work hard work smart 阅读(171) 评论(0) 编辑 收藏 举报使用场景较少
/** * 使用场景较少 */ @Slf4j public class LockExample3 { private final Map<String, Data> map = new TreeMap<>(); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock(); public Data get(String key){ readLock.lock(); try{ return map.get(key); }finally { readLock.unlock(); } } public Set<String> getAllKeys(){ readLock.lock(); try{ return map.keySet(); }finally { readLock.unlock(); } } public Data put(String key, Data value){ //没有读写操作,才能获得写锁。 不适合写少,读多的情况,将导致饥饿情况,一直无法获得写锁。 writeLock.lock(); try{ return map.put(key, value); }finally { readLock.unlock(); } } class Data{ } public static void main(String[] args) throws InterruptedException { } private static void add(){ } }
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!