zoukankan      html  css  js  c++  java
  • 8. 读写锁

    ReadWriteLock: 一个用于只读操作,一个用于写入操作;读的时候可以由多个线程进行,写的时候只能有一个。

    • 读-读:可以共存
    • 读-写:不可共存
    • 写-写:不可共存

    读锁:共享锁

    写锁:独享锁

    代码示例

    package pers.vincent.matrix.subject.readwrite;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.locks.ReadWriteLock;
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    public class ReadWriteLockTest {
    
        public static void main(String[] args) {
            MyCache cache = new MyCache();
    
    
            for (int i = 1; i <=5 ; i++) {
                new Thread(()->{
                    cache.write();
                }).start();
            }
    
    
            for (int i = 1; i <=5 ; i++) {
                new Thread(()->{
                    cache.read();
                }).start();
            }
        }
    
    }
    
    class MyCache{
        private volatile Map<String, Object> map = new HashMap<String, Object>();
    
        private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    
        // 写入
        public void write(){
    
            try{
                readWriteLock.writeLock().lock();
    
                System.out.println(Thread.currentThread().getName()+"写入");
    
                map.put(Thread.currentThread().getName(), Thread.currentThread().getName());
    
                System.out.println(Thread.currentThread().getName()+"写入ok");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                readWriteLock.writeLock().unlock();
            }
    
        }
    
        // 读取
        public void read(){
            try{
                readWriteLock.readLock().lock();
    
                System.out.println(Thread.currentThread().getName()+"读取");
    
                map.get(Thread.currentThread().getName());
    
                System.out.println(Thread.currentThread().getName()+"读取ok");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                readWriteLock.readLock().unlock();
            }
    
        }
    
    }
    
  • 相关阅读:
    python学习的第20天内置模块之sys、os、os下的path、random、shutil
    【数据结构】数组
    【INDEX】【C和C++】学习汇总
    【Spark】Spark环境配置
    【Scala】一些没有的关键字和声明
    【Scala】异常控制
    二叉树的最大深度
    回文链表
    环形链表
    删除链表的倒数第N个节点
  • 原文地址:https://www.cnblogs.com/blackBlog/p/13451469.html
Copyright © 2011-2022 走看看