其他分享
首页 > 其他分享> > ReadWriteLock JUC多线程读写锁

ReadWriteLock JUC多线程读写锁

作者:互联网

package com.pa.test.JUC.lock;

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

/**
 * ReadWriteLock
 * 读 读  可以共存
 * 读 写  不能共存
 * 写 写  不能共存
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        MyLock myLock = new MyLock();
        for (int i = 1; i <= 5; i++) {
            final int temp = i;
            new Thread(()->{
                myLock.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        for (int i = 1; i <= 5; i++) {
            final int temp = i;
            new Thread(()->{
                myLock.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}

class MyLock{
    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() + "写入ok");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }
    //读取 可以多个线程执行
    public void get(String key){
        readWriteLock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取ok");
    }
}

标签:JUC,java,String,currentThread,ReadWriteLock,System,key,多线程,out
来源: https://blog.csdn.net/weixin_43688217/article/details/121142666