ReentrantReadWriteLock:
在读的时候可以多个线程一起读, 在写的时候,只能一个线程写。
场景:
用Map模拟一个缓存,put方法是用写锁加锁, get用读锁加锁。
public class Test4 {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCache.put(temp + "", temp + "");
}, String.valueOf(i)).start();
}
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCache.get(temp + "");
}, String.valueOf(i)).start();
}
}
}
class MyCache {
private volatile Map<String, Object> map = new HashMap<>();
private ReadWriteLock lock = new ReentrantReadWriteLock();
//写 只有一个线程写
public void put(String key, Object value) {
lock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + "写入:" + value);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入完毕:" + value);
lock.writeLock().unlock();
}
//读 可以多个线程读
public Object get(String key) {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "读取:");
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取完毕:" + o);
lock.readLock().unlock();
return null;
}
}