ReadWriteLock读写锁
ReadwriteLock维护一对关联的locks , 一个用于只读操作,一个用于写入。read lock可以由多个阅读器线程同时进行,只要没有作者。write lock是独家的。
public class ReadWriteLockTest {
public static void main(String[] args) {
MyCache cache = new MyCache();
for (int j = 1; j <= 5; j++) {
final int temp = j;
new Thread(()->{
cache.put(temp, temp);
},String.valueOf(j)).start();
}
for (int j = 1; j <= 5; j++) {
final int temp = j;
new Thread(()->{
cache.get(temp);
},String.valueOf(j)).start();
}
}
}
class MyCache{
private volatile Map<Integer, Object> map = new HashMap<Integer, Object>();
ReadWriteLock lock = new ReentrantReadWriteLock();
public void put(Integer key,Object value) {
try {
lock.writeLock().lock();
System.out.println(Thread.currentThread().getName()+"写入"+value);
map.put(key, value);
System.out.println(Thread.currentThread().getName()+"写入 完毕");
} catch (Exception e) {
e.getStackTrace();
} finally {
lock.writeLock().unlock();
}
}
public void get(Integer key) {
try {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName()+"读取"+key);
map.get(key);
System.out.println(Thread.currentThread().getName()+"读取 完毕");
} catch (Exception e) {
e.getStackTrace();
} finally {
lock.readLock().unlock();
}
}
}
方法
ReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock.lock(); 加读锁
lock.readLock.unlock(); 解读锁
lock.writeLock().lock(); 加写锁
lock.writeLock().unlock(); 解写锁