引出
读写锁的设计主要参考读写锁的设计模式:https://blog.csdn.net/qq_43040688/article/details/105857920
使用
public class ReadWriteLockTest {
private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
private static final Lock readLock = lock.readLock();
private static final Lock writeLock = lock.writeLock();
private static final List<Long> data = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
new Thread(()->write(),"write-1").start();
Thread.sleep(1000);
new Thread(()->read(),"read-1").start();
new Thread(()->read(),"read-2").start();
}
public static void write(){
try{
writeLock.lock();
data.add(System.currentTimeMillis());
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}
public static void read(){
try{
readLock.lock();
for (Long datum : data) {
System.out.println(datum);
}
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + "************************");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readLock.unlock();
}
}
}
- 其他API与ReentrantLock相似,详情看:https://blog.csdn.net/qq_43040688/article/details/105958719