ReadWriteLock

ReadWriteLock

  • ReadWriteLock
  • /**
     * 独占锁(写锁)
     * 一次只能被一个线程占有
     * 共享锁(读锁) 多个线程可以同时占有
     *
     * ReadWriteLock
     * 读-读  可以共存!
     * 读-写  不能共存!
     * 写-写  不能共存!
     */
    public class Test04 {
        public static void main(String[] args) throws InterruptedException {
            MyCacheLock myCache = new MyCacheLock();
            //写入
            for (int i = 0; i < 5; i++) {
                final int count = i;
                new Thread(() -> {
                    myCache.put(count + " ", count + " ");
                }, String.valueOf(i)).start();
            }
            //写入
            for (int i = 0; i < 5; i++) {
                final int count = i;
                new Thread(() -> {
                    myCache.get(count + " ");
                }, String.valueOf(i)).start();
            }
        }
    }
    
    //加锁的自定义缓存
    class MyCacheLock {
        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() + "写入完成");
            } 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);
                Object obj = map.get(key);
                System.out.println(Thread.currentThread().getName() + "读取完成");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                readWriteLock.readLock().unlock();
            }
        }
    }
    
    //自定义缓存  : 会出现插队写入
    /* 会出现插队写入   :
            0写入0
            4写入4
            4写入完成
            3写入3
            3写入完成*/
    class MyCache {
        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() + "写入完成");
        }
        //取,读
        public void get(String key) {
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object obj = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完成");
        }
    }
    
上一篇:龟兔赛跑问题(并发)


下一篇:设置 WPF 的全球化语言