一、ReentrantReadWriteLock
两个线程同时读取,不会互斥:
@Slf4j
public class ReadWriteLockTest {
public static void main(String[] args) throws InterruptedException {
DataContainer dataContainer = new DataContainer();
new Thread(dataContainer::read, "t1").start();
//Thread.sleep(1000);
new Thread(dataContainer::read, "t2").start();
}
}
@Slf4j
class DataContainer {
private Object data;
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
private ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
public Object read() {
readLock.lock();
log.debug("获取读锁");
try {
log.debug("读取");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return data;
} finally {
readLock.unlock();
log.debug("释放读锁");
}
}
public void write() {
writeLock.lock();
log.debug("获取写锁");
try {
log.debug("写入");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
writeLock.unlock();
log.debug("释放写锁");
}
}
}
13:52:32.177 [t2] DEBUG juc.readwrite.DataContainer - 获取读锁
13:52:32.177 [t1] DEBUG juc.readwrite.DataContainer - 获取读锁
13:52:32.180 [t1] DEBUG juc.readwrite.DataContainer - 读取
13:52:32.180 [t2] DEBUG juc.readwrite.DataContainer - 读取
13:52:33.181 [t1] DEBUG juc.readwrite.DataContainer - 释放读锁
13:52:33.181 [t2] DEBUG juc.readwrite.DataContainer - 释放读锁
一个线程读取,一个线程写入,会互斥:
@Slf4j
public class ReadWriteLockTest {
public static void main(String[] args) throws InterruptedException {
DataContainer dataContainer = new DataContainer();
new Thread(dataContainer::read, "t1").start();
Thread.sleep(1000);
new Thread(dataContainer::write, "t2").start();
}
}
@Slf4j
class DataContainer {
private Object data;
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
private ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
public Object read() {
readLock.lock();
log.debug("获取读锁");
try {
log.debug("读取");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();