package com.example.rw;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @ClassName ReadWriteLockDemo
* @description: TODO
* @author: went
* @Date 2021/7/15 7:50 上午
**/
public class ReadWriteLockDemo {
private static MyCache cache = MyCache.INSTANCE;
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
final String temp = i + "";
new Thread(()->{
try {
cache.put(temp, temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Writer-" + i).start();
}
//写锁会阻塞 其后的读锁
TimeUnit.SECONDS.sleep(10);
for (int i = 0; i < 10; i++) {
final String temp = i + "";
new Thread(()->{
try {
cache.get(temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "Reader-" + i).start();
}
}
}
enum MyCache {
//单例
INSTANCE;
private static final Map<String, Object> cache = new HashMap<>();
//公平锁
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(false);
private Lock writeLock = readWriteLock.writeLock();
private Lock readLock = readWriteLock.readLock();
//写数据
public void put(String key, Object value) throws InterruptedException {
try {
// TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + " 尝试写入 》》");
writeLock.lock();
//--------------------- 开始排他 ----------------------------------------
System.out.println(Thread.currentThread().getName() + " 开始写入...");
cache.put(key, value);
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + " 完成写入...");
//--------------------- 结束排他 ----------------------------------------
} finally {
writeLock.unlock();
}
}
//读数据
public Object get(String key) throws InterruptedException {
try {
// TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + " 尝试读取 《《");
readLock.lock();
// ---------------------------读共享--------------------------------
System.out.println(Thread.currentThread().getName() + " 开始读取...");
// TimeUnit.SECONDS.sleep(1);
final Object o = cache.get(key);
System.out.println(Thread.currentThread().getName() + " 完成读取..." + o);
return o;
// ---------------------------读共享--------------------------------
}finally {
readLock.unlock();
}
}
}
读写锁示例
最新推荐文章于 2023-02-25 10:41:49 发布