ReadWriteLock(共享锁(读锁),独享锁(写锁))

2022/5/3 23:15:50

本文主要是介绍ReadWriteLock(共享锁(读锁),独享锁(写锁)),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

读读 可以共存
读写 不可以共存
写写 不可以共存

package com.luoKing.ReadWrite;

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

public class ReadWritelock {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }, String.valueOf(i)).start();
        }

    }


}



/*
 *
 * 自定义缓存
 * */

//加读写锁,这样可以实现读的时候可以多个线程读(共享锁或者说读锁),写的时候只允许一个线程写(独享锁,写锁)
class MyCacheLock {
    private volatile Map<String, String> map = new HashMap<>();
    final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 

    public void put(String key, String 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(); //共享锁或者说读锁
        try {
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }


    }
}

//没有加锁,并发一定会发生问题
class MyCache {
    private volatile Map<String, String> map = new HashMap<>();

    public void put(String key, String value) {
        System.out.println(Thread.currentThread().getName() + "写入" + key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "写入OK");
    }

    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "读取" + key);
        map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取OK");

    }
}


这篇关于ReadWriteLock(共享锁(读锁),独享锁(写锁))的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程