ReadWriteLock 读写锁

读写锁 ReadWriteLock

缓存工具类

package com.wdg.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description: 自定义缓存加读写锁
 * @author: WuDG/1490727316@qq.com
 * @date: 2021/3/17 15:46
 */
public class MyCacheLock {
    private volatile Map<String, Object> map = new HashMap<>(1<<4);

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object value){
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key+","+value);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"写入"+key+","+value+",写入完毕!!!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }

    public Object get(String key){
        lock.readLock().lock();
        Object o = null;
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取"+key+",读取完毕!!!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        return o;
    }
}

执行

package com.wdg.concurrent;

/**
 * @description: 读写锁实例
 * @author: WuDG/1490727316@qq.com
 * @date: 2021/3/17 15:46
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock cache = new MyCacheLock();
        // 写入
        for (int i = 0; i < 9; i++) {
            final int tmp = i;
            new Thread(() -> cache.put(String.valueOf(tmp),String.valueOf(tmp)),String.valueOf(i)).start();
        }

        // 读取
        for (int i = 0; i < 9; i++) {
            final int tmp = i;
            new Thread(() -> {
                Object o = cache.get(String.valueOf(tmp));
                System.out.println("值:"+o);
            },String.valueOf(i)).start();
        }
    }
}
# java  并发 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×