读写锁(ReadWriteLock),顾名思义,就是在读写某文件时,对该文件上锁。
1. ReentrantReadWriteLock
- 三部曲:
- 加锁;
- 读写操作;
- 解锁;(为保证解锁操作一定执行,通常将其置于 finally 代码段内)
2. 将读写锁应用于集合类上
使得集合线程安全。一个线程安全的字典(map)如下:
class RWDictionary {
private final Map<String, Data> m = new TreeMap<String, Data>();
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock r = rwl.readLock();
private final Lock w = rwl.writeLock();
public Data get(String key) {
r.lock();
try { return m.get(key); }
finally { r.unlock(); }
}
public String[] allKeys() {
r.lock();
try { return m.keySet().toArray(); }
finally { r.unlock(); }
}
public Data put(String key, Data value) {
w.lock();
try { return m.put(key, value); }
finally { w.unlock(); }
}
public void clear() {
w.lock();
try { m.clear(); }
finally { w.unlock(); }
}
}