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");
}
}
标签:String,Thread,写锁,ReadWriteLock,System,读锁,key,currentThread,out 来源: https://www.cnblogs.com/luoking/p/16219400.html