package readwrite;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Mycache {
private volatile Map<String, Object> map = new HashMap<>();
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String key, Object value) {
//添加写锁
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "正在写操作" + key);
TimeUnit.MICROSECONDS.sleep(300);
//写数据
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写完了" + key);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
//取数据
public Object get(String key) {
//添加读锁
readWriteLock.writeLock().lock();
Object result = null;
try {
System.out.println(Thread.currentThread().getName() + "正在读操作" + key);
TimeUnit.MICROSECONDS.sleep(300);
result = map.get(key);
System.out.println(Thread.currentThread().getName() + "读完了" + key);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
return result;
}
}
}
public class ReadWriteLock {
public static void main(String[] args) {
Mycache mycache = new Mycache();
//放数据
for (int i = 1; i <= 5; i++) {
final int num = i;
new Thread(() -> {
mycache.put(num + "", num + " ");
}, String.valueOf(i)).start();
}
//取数据
for (int i = 1; i <= 5; i++) {
final int num = i;
new Thread(() -> {
mycache.get(num + "");
}, String.valueOf(i)).start();
}
}
}
/**
* 添加读写锁之前
* 1正在读操作1
* 3正在写操作3
* 3正在读操作3
* 0正在读操作0
* 5正在写操作5
* 4正在写操作4
* 2正在读操作2
* 2正在写操作2
* 1正在写操作1
* 3取完了3
* 3写完了3
* 1取完了1
* 4写完了4
* 2取完了2
* 5写完了5
* 0取完了0
* 2写完了2
* 1写完了1
**/
/**
*4正在读操作4
* 4读完了4
* 5正在读操作5
* 5读完了5
* 2正在读操作2
* 2读完了2
* 1正在读操作1
* 1读完了1
* 2正在写操作2
* 2写完了2
* 3正在读操作3
* 3读完了3
* 1正在写操作1
* 1写完了1
* 3正在写操作3
* 3写完了3
* 5正在写操作5
* 5写完了5
* 4正在写操作4
* 4写完了4
*/
原文:https://www.cnblogs.com/chickenleg/p/15041007.html