JUC 读写锁 ReadWriteLock
一、语法
private ReadWriteLock rwLock = new ReentrantReadWriteLock(); // 上锁 rwLock.writeLock().lock(); // 释放锁 rwLock.writeLock().unlock();
二、案例
存入、读取 map数据
package com.wt.readwrite; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @Description: TODO * @Author: 1872428 * @Date: 2025/6/2 8:53 * @Version: 1.0 **/ class OperationData{ private volatile Map<String, Object> map = new HashMap<>(); private ReadWriteLock rwLock = new ReentrantReadWriteLock(); // 保存 public void save(String key, Object object){ try { rwLock.writeLock().lock(); System.out.println(Thread.currentThread().getName()+"正在写入数据" +key); map.put(key, object); TimeUnit.MICROSECONDS.sleep(300); System.out.println(Thread.currentThread().getName()+"写入完成" + key); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwLock.writeLock().unlock(); } } // 获取 public Object getData(String key){ Object result = null; try { rwLock.readLock().lock(); System.out.println(Thread.currentThread().getName()+"正在读取数据" + key); result = map.get(key); TimeUnit.MICROSECONDS.sleep(300); System.out.println(Thread.currentThread().getName()+"读取完成" + key); } catch (InterruptedException e) { e.printStackTrace(); } finally { rwLock.readLock().unlock(); } return result; } } public class Demon { public static void main(String[] args) { OperationData operationData = new OperationData(); // 存 for (int i = 0; i < 5; i++) { final int num = i; new Thread(()->{ operationData.save(num + "", num +""); }, "AA").start(); } try { TimeUnit.MICROSECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } // 取 for (int i = 0; i < 5; i++) { final int num = i; new Thread(()->{ operationData.getData(num + ""); }, "BB").start(); } } }