JAVA多线程——ReadWriteLock

1. 新建资源类

/**
 * @author huangdh
 * @version 1.0
 * @description:
 * @date 2022-10-30 15:41
 */
// 资源类
public class MyCache {

    /**
     * 写锁:独占锁
     * 读锁:共享锁
     */

    // 创建map集合
    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);

            TimeUnit.MILLISECONDS.sleep(300);

            map.put(key,value);
            System.out.println(Thread.currentThread().getName() + "写完了" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    // 读取数据
    public Object get(String key){

        Object object = null;

        // 上锁
        readWriteLock.readLock().lock();
        try {

            System.out.println(Thread.currentThread().getName() + "正在读取操作" + key);
            TimeUnit.MILLISECONDS.sleep(300);
            object = map.get(key);
            System.out.println(Thread.currentThread().getName() + "数据读取完毕" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
        return object;
    }
}

2. 操作资源类


/**
 * @author huangdh
 * @version 1.0
 * @description:
 * @date 2022-10-30 16:13
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 5; i++) {

            final int num = i;
            new Thread(()->{
                myCache.put(String.valueOf(num),num);
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {

            final int num = i;
            new Thread(()->{
                myCache.get(String.valueOf(num));
            },String.valueOf(i)).start();
        }
    }
}

3. 程序运行结果

0正在写数据0
0写完了0
1正在写数据1
1写完了1
2正在写数据2
2写完了2
3正在写数据3
3写完了3
4正在写数据4
4写完了4
0正在读取操作0
1正在读取操作1
2正在读取操作2
3正在读取操作3
4正在读取操作4
4数据读取完毕4
3数据读取完毕3
1数据读取完毕1
0数据读取完毕0
2数据读取完毕2

 

posted @ 2022-11-20 15:11  BlogMemory  阅读(13)  评论(0编辑  收藏  举报