独占锁(写锁)一次只能被一个线程占有
共享锁(读锁)多个线程可以同时占有
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();}}}
