一. 独占(写)锁与共享(读)锁
独占(写)锁与共享(读)锁也可以叫读写锁
简单理解就是,我写的时候不能被其他线程干扰,需要独占线程资源,
我读的时候可以共享并发进行。
二. 实现读写锁
模拟缓存来实现读写锁
手写一个缓存需要三点:
1.存值 put(key, value)
2.取值 get(key)
3.清空缓存 clear
class Mycache {
//缓存空间
private volatile Map<String, Object> map = new HashMap<>();
//读写锁
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
//存值
public void put(String key, Object value) {
rwLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "\t 正在写入: " + key);
//模拟网路拥堵,暂停 300毫秒
try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
//存
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t 写入完成: ");
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.writeLock().unlock();
}
}
//取值
public void get(String key) {
rwLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "\t 正在读取: ");
//模拟网路拥堵,暂停 300毫秒
try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
//取
Object result = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t 读取完成: " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.readLock().unlock();
}
}
//清空缓存
public void clearMap() {
map.clear();
}
}
测试缓存读写锁
public static void main(String[] args) {
Mycache mycache = new Mycache();
//开五个线程 写
for (int i = 1; i <= 5; i++) {
final int tempInt = i;
new Thread(() -> {
mycache.put(tempInt + "", tempInt + "");
}, String.valueOf(i)).start();
}
//开五个线程 读
for (int i = 1; i <= 5; i++) {
final int tempInt = i;
new Thread(() -> {
mycache.get(tempInt + "");
}, String.valueOf(i)).start();
}
}
运行结果
保证了,写独占,读共享。