标签:
内容:利用ReentrantReadWriteLock来包装Map,从而使它能在多个读线程之间被安全分享,并且仍然能避免“读-写”或“写-写”冲突。记住重要的一点是:读-写锁实现的加锁策略中,允许多个读操作同时进行,但每次只允许一个写操作。
public class ReadWriteMap<K, V> {
private final Map<K, V> map;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock r = lock.readLock();
private final Lock w = lock.writeLock();
public ReadWriteMap(Map<K, V> map) {
this.map = map;
}
public V put(K key, V value) {
w.lock();
System.out.println("获取写锁");
try {
return map.put(key, value);
} finally {
w.unlock();
System.out.println("释放写锁");
}
}
public V get(K key) {
r.lock();
System.out.println("获取读锁");
try {
return map.get(key);
} finally {
r.unlock();
System.out.println("释放读锁");
}
}
public static void main(String[] args) throws InterruptedException {
final Map<Integer, String> map = new HashMap<Integer, String>();
final ReadWriteMap<Integer, String> readWriteMap = new ReadWriteMap<Integer, String>(map);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i <= 10; i++) {
final int tmp = i;
executorService.execute(new Runnable() {
@Override
public void run() {
readWriteMap.put(tmp, tmp+"");
}
});
if ((i & 1) == 1) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(readWriteMap.get(new Random().nextInt(6)));
}
});
}
}
executorService.shutdown();
}
}标签:
原文地址:http://blog.csdn.net/u011345136/article/details/46059237