ReadWriteLock读写锁
概念:
读写锁:存在着两个锁,一个读锁(共享锁)
,一个写锁(独占锁)
从文档中获取到只有一个实现类 :ReentrantReadWriteLock
/**独占锁(读锁):
* 共享锁(写锁):
* */
public class ReadWriteLockTest { public static void main(String[] args) { // MyLock myLock = new MyLock(); MyLock2 myLock = new MyLock2(); //只进行写入操作 for (int i =1; i <=5 ; i++) { final int temp=i; new Thread(()->{ myLock.Put(temp+"",temp+""); },String.valueOf(i)).start(); } //只进行读取操作 for (int i = 1; i <=5 ; i++) { final int temp=i; new Thread(()->{ myLock.Get(temp+""); },String.valueOf(i)).start(); } } }
//自定义缓存
class MyLock{ private volatile Map<String , Object> map = new HashMap(); //写入操作 , public void Put(String key ,Object value){ System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key , value); System.out.println(Thread.currentThread().getName()+"写入OK"); } //读取操作 public void Get(String key){ System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取OK"); } }
//加入ReadWriteLock(读写锁)进行操作
class MyLock2{ 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()+"写入"+key); map.put(key , value); System.out.println(Thread.currentThread().getName()+"写入OK"); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } //读取操作 public void Get(String key){ //读锁(共享锁),可以多个线程同时进行读取 readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取OK"); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.readLock().unlock(); } } }
加入读写锁能够保证,写入时只有一个线程进行写入,读取时可以多个线程同时进行