读写锁

ReadWriteLock

/**
 * 独占锁(写锁):一次只能被一个线程占有
 * 共享锁(读锁):多个线程可以同时占有
 * ReadWriteLock*/
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache cache = new MyCache();

        //写入
        for (int i = 1; i <= 5; i++){
            final int temp = i;
            new Thread(()->{
                cache.write("第"+temp+"写","新年快乐,牛气冲天!");
            },String.valueOf(temp)).start();
        }

        //读取
        for (int i = 1; i <= 5; i++){
            final int temp = i;
            new Thread(()->{
                cache.read("第"+temp+"写");
            },String.valueOf(temp)).start();
        }
    }
}

/*自定义缓存*/
class MyCache{
    private volatile Map map = new HashMap<>();
    //读写锁,更加细粒度的控制
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /*存,写入的时候,只希望同时只有一个线程去写。*/
    public void write(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 read(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始读取"+key);
            Object out = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取成功!结果:"+out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}

你可能感兴趣的:(读写锁)