读写锁--DEMO
package com.demo.read.write.lock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 读写锁案例 * @author Administrator * */ public class ReadWriteLockDemo { private Map<String, Object> map = new HashMap<String, Object>(); private ReadWriteLock rwLock = new ReentrantReadWriteLock(); private Lock rLock = rwLock.readLock(); private Lock wLock = rwLock.writeLock(); public void put(String key, Object value) throws InterruptedException { wLock.lock(); System.out.println(Thread.currentThread().getName() + " 写操作执行了。。。"); Thread.sleep(1000); try { map.put(key, value); } finally { System.out.println(Thread.currentThread().getName() + " 写操作执行完成了。。。"); wLock.unlock(); } } public Object get(String key) throws InterruptedException { rLock.lock(); System.out.println(Thread.currentThread().getName() + " 读操作执行了。。。"); Thread.sleep(1000); try { return map.get(key); } finally { System.out.println(Thread.currentThread().getName() + " 读操作执行完成了。。。"); rLock.unlock(); } } }