在多线程存取数据时,如果不加锁就会导致数据有误,线程安全问题。可是如果把写入、读取都加锁,写入还好,读取也变成一个一个的读取,就会比较慢。所以读写锁就是来解决:
写入加锁,读取的时候可以多个读取,也就是独占锁(写)、共享锁(读)
- package com.quxiao.controller;
-
-
- import java.util.*;
- import java.util.concurrent.*;
- import java.util.concurrent.locks.ReentrantReadWriteLock;
- import java.util.stream.Collectors;
-
- /**
- * @program: package1
- * @author: quxiao
- * @create: 2023-09-27 15:22
- **/
- public class t3 {
- public static void main(String[] args) {
- t t = new t();
- for (int i = 0; i < 30; i++) {
- final int tem = i;
- new Thread(() -> {
- t.put(tem + "", tem + "");
- t.get(tem + "");
- }).start();
- }
- }
-
- static class t {
- Map
map = new HashMap<>(); - ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
-
- void put(String key, String val) {
- lock.writeLock().lock();
- try {
- System.out.println(key + "写");
- map.put(key, val);
- System.out.println(key + "写ok");
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- lock.writeLock().unlock();
- }
- }
-
- void get(String key) {
- lock.readLock().lock();
- try {
- System.out.println(key + "读");
- String s = map.get(key);
- System.out.println(key + "读ok:" + s);
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- lock.readLock().unlock();
- }
- }
- }
- }