独占锁(写锁)一次只能被一个线程占有
共享锁(读锁)多个线程可以同时占有
public class LockTest {
public static void main(String[] args) throws InterruptedException {
CacheDemo cacheDemo = new CacheDemo();
// 写入
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(()->{
cacheDemo.put(temp + "", temp + "");
}, String.valueOf(i)).start();
}
// 读取
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(()->{
cacheDemo.get(temp + "");
}, String.valueOf(i)).start();
}
}
}
class CacheDemo {
private volatile Map<String, Object> map = new HashMap<>();
// 读写锁
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String key, Object value) {
// 加写锁
readWriteLock.writeLock().lock();
try {
System.out.println("写入:" + Thread.currentThread().getName());
map.put(key, value);
System.out.println("写完:" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
public void get(String key) {
readWriteLock.readLock().lock();
try {
System.out.println("读取:" + Thread.currentThread().getName());
map.get(key);
System.out.println("读完:" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}