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();
            }
    
        }
    
    }
    
  • 相关阅读:
    httpcontext in asp.net unit test
    initialize or clean up your unittest within .net unit test
    Load a script file in sencha, supports both asynchronous and synchronous approaches
    classes system in sencha touch
    ASP.NET MVC got 405 error on HTTP DELETE request
    how to run demo city bars using sencha architect
    sencha touch mvc
    sencha touch json store
    sencha touch jsonp
    51Nod 1344:走格子(贪心)
  • 原文地址:https://www.cnblogs.com/blackBlog/p/13451469.html
Copyright © 2011-2022 走看看