讀寫鎖--DEMO
阿新 • • 發佈:2018-12-06
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) throwsInterruptedException { 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(); } } }