使用ReadWriteLock的读写锁 实现 模拟缓存的 功能
package cn.zto.lock;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
//模仿缓存
public class CacheDateTest {
ReadWriteLock rwl = new ReentrantReadWriteLock();
Map<Object, Object> map = new HashMap<Object, Object>();
public Object get(Object key){
rwl.readLock().lock();
Object value = null;
boolean flag ;
value = map.get(key);
if (value == null) {
flag = false;
rwl.readLock().unlock();
rwl.writeLock().lock();
if (!flag) {
value = " 初始化 ";
map.put(key, value);
flag = true;
}
rwl.writeLock().unlock();
rwl.readLock().lock();
}
rwl.readLock().unlock();
return value;
}
}