package com.atguigu.thread.writereadlock;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读写锁 ReentrantReadWriteLock
*/
public class WriteAndReadLockDemo
{
public static void main(String[] args)
{
Myache myache = new Myache();
// 五个写线程
for (int i = 1; i < 6; i++ )
{
final int tempInt = i;
new Thread(() -> {
myache.put(tempInt + "", tempInt + "");
}, String.valueOf(i)).start();
}
// 五个读线程
for (int i = 1; i < 6; i++ )
{
final int tempInt = i;
new Thread(() -> {
myache.get(tempInt + "");
}, String.valueOf(i)).start();
}
}
}
class Myache
{
private volatile Map<String, Object> map = new HashMap<>();
// private Lock lock = new ReentrantLock();
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
public void put(String key, Object value)
{
rwLock.writeLock().lock();
try
{
System.out.println(Thread.currentThread().getName() + "\t 正在写入" + key);
try
{
TimeUnit.MILLISECONDS.sleep(300);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t 正在完成");
}
finally
{
rwLock.writeLock().unlock();
}
}
public void get(String key)
{
rwLock.readLock().lock();
try
{
System.out.println(Thread.currentThread().getName() + "\t 正在读取");
try
{
TimeUnit.MILLISECONDS.sleep(300);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Object result = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t 读取完成" + result);
}
finally
{
rwLock.readLock().unlock();
}
}
}
执行结果
2 正在写入2
2 正在完成
3 正在写入3
3 正在完成
1 正在写入1
1 正在完成
2 正在读取
1 正在读取
3 正在读取
1 读取完成1
3 读取完成3
2 读取完成2
通过执行结果可以看出:写操作时是原子操作且是独占锁,不允许其他线程进行操作。读取时的锁是共享锁(读取到完成的顺序不一致)。