ReentrantReadWriteLock讀寫鎖簡單原理案例證明
阿新 • • 發佈:2021-01-31
## ReentrantReadWriteLock存在原因?
---
我們知道List的實現類ArrayList,LinkedList都是非執行緒安全的,Vector類通過用synchronized修飾方法保證了List的多執行緒非安全問題,但是有個缺點:**讀寫同步,效率低下**。於是就出現了CopyOnWriteArrayList,它通過寫時複製陣列實現了讀寫分離,**提高了多執行緒對List讀的效率,適合多讀少些的情況**。同理:我們知道ReentrantLock,它是一把獨佔的鎖,是用來控制執行緒同步的,如果我們用ReentrantLock來實現ArrayList安全,能否達到CopyOnWriteArrayList同樣的效果呢?
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author :jiaolian
* @date :Created in 2021-01-26 15:49
* @description:ReentrantReadWriteLock多讀少寫的場景
* @modified By:
* 公眾號:叫練
*/
public class MultReadTest {
private static class MyList {
private final ReentrantReadWriteLock REENTRANT_READ_WRITE_LOCK = new ReentrantReadWriteLock();
private final ReentrantReadWriteLock.WriteLock WRITE_LOCK = REENTRANT_READ_WRITE_LOCK.writeLock();
private final ReentrantReadWriteLock.ReadLock READ_LOCK = REENTRANT_READ_WRITE_LOCK.readLock();
priv