ReadWriteLock读写锁
ReadWriteLock读写锁
-
ReadWriteLock只允许一个线程修改,但是get()方法只读,不修改数据,实际上允许多个线程同时调用,使用
ReadWriteLock
可以解决这个问题 -
适合读多写少的场景
-
源码
public interface ReadWriteLock {
Lock readLock();
Lock writeLock();
}
- 实现类:ReentrantReadWriteLock
- 读锁(共享锁),写锁(独占锁)
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class MyReadWriteLock {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 0; i < 6; i++) {
final int temp = i;
new Thread(() -> {
// lambda无法访问到外部的变量
myCache.put(temp + "", "value:" + temp);
}, String.valueOf(i)).start();
}
for (int i = 0; i < 6; i++) {
final int temp = i;
new Thread(() -> {
myCache.get(temp + "");
}, String.valueOf(i)).start();
}
}
}
class MyCache {
private final Map<String, Object> map = new HashMap<>();
// 读写锁
private final ReadWriteLock lock = new ReentrantReadWriteLock();
// 只有一个可以写
public void put(String key, Object value) {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "写入" + value);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写完毕");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
// 可以多个同时读
public void get(String key) {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "读取" + map.get(key));
System.out.println(Thread.currentThread().getName() + "读完毕");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
}