package com.example.juc;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @program: demo
* @description: 读写锁
* @author: ZCY
**/
public class ReadWriteLockDemo {
public static void main(String[] args) {
Cache cache = new Cache();
//读操作
for (int i = 1; i <= 5; i++) {
int tmp = i;
new Thread(() -> {
cache.read(tmp + "");
}, String.valueOf(i)).start();
}
//写操作
for (int i = 1; i <= 5; i++) {
int tmp = i;
new Thread(() -> {
cache.write(tmp + "", tmp + "");
}, String.valueOf(i)).start();
}
}
}
//自定义缓存
class Cache {
private volatile Map<String, Object> map=new HashMap<>();
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void read(String key) {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "读取" + key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取结束");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
public void write(String key, Object value) {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "写入" + key);
Object o = map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入结束");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
}
Lock读写锁
最新推荐文章于 2022-10-26 05:00:00 发布