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();
        }

    }

}
posted @ 2020-08-07 11:01  湘北不会输的  阅读(71)  评论(0编辑  收藏  举报