Java中的读写锁 ReentrantReadWriteLock
【推荐阅读】微服务还能火多久?>>> 使用场景较少 /** * 使用场景较少 */ @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){ //没有读写操作,才能获得写锁。 不适合写少,读多的情况,将导致饥饿情况