ReadWriteLock使用记录
2022-12-15 本文已影响0人
arkliu
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockTest {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 0; i < 5; i++) {
final int tmp = i;
new Thread(()->{
myCache.write(""+tmp, tmp);
},"线程"+i).start();
}
for (int i = 0; i < 5; i++) {
final int tmp = i;
new Thread(()->{
myCache.read(""+tmp);
},"线程"+i).start();
}
}
}
class MyCache {
private Map<String, Object>cache = new HashMap<String, Object>();
// 创建读写锁
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void write(String key, Object value) {
readWriteLock.writeLock().lock(); // 写锁lock
try {
System.out.println(Thread.currentThread().getName()+"正在写入"+key);
cache.put(key, value);
System.out.println(Thread.currentThread().getName()+"写入"+key+"完成");
} catch (Exception e) {
} finally {
readWriteLock.writeLock().unlock(); //写锁unlock
}
}
public Object read(String key) {
Object temp = null;
readWriteLock.readLock().lock();// 读锁lock
try {
System.out.println(Thread.currentThread().getName()+"正在读取"+key);
cache.get(key);
System.out.println(Thread.currentThread().getName()+"读取"+key+"完成");
} catch (Exception e) {
} finally {
readWriteLock.readLock().unlock(); ////读锁unlock
}
return temp;
}
}