使用场景较少
/**
* 使用场景较少
*/
@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(){
}
}
来源:oschina
链接:https://my.oschina.net/u/4342092/blog/3234626