Read-write lock of ReenTrantLock

Read-write lock of ReenTrantLock

In the last few articles, we introduced the synchronization-related locks Synchronize locks and JDK's JUC locks and ReentrantLock locks. Now I am going to introduce the JDK read-write lock (the test code is borrowed from someone else's blog, I will only make a summary here).

First introduce this read-write lock ReentrantReadWriteLock

This read-write lock is also under the JDK tool java.util.concurrent.locks package. Unlike ReentrantLock, ReentrantLock inherits Lock, and ReentrantReadWriteLock inherits ReadWriteLock.

Everyone knows that multi-threaded synchronization locking will greatly affect efficiency, so a read-write lock ReentrantReadWriteLock class is provided in the JDK, which can speed up operation efficiency. In some methods that do not need to manipulate instance variables, you can use read Write lock ReentrantReadLock to improve the code running speed of this method.
Read-write locks are divided into read locks and write locks:

private ReentrantReadWriteLock lock =  new ReentrantReadWriteLock()
 lock.readLock().lock(); // 读锁
 lock.writeLock().lock();// 写锁

How to understand it?

Read lock: Generally used in business programs that do not operate on shared resources, only read resources, not write operations. In this way, there will be no thread insecurity issues for shared resources. Therefore, in order for multiple threads to efficiently read resources, read locks will allow multiple threads to acquire locks to access resource information.

Write lock: Generally used in business programs that have shared resource operations. Because write operations may cause thread insecurity, multiple threads should not be allowed to obtain locks at the same time, and an exclusive lock mechanism is required. Therefore, the read lock is an exclusive lock, and the lock can be obtained by other threads only after the previous thread ends.

It can be seen from this that
if there is a multi-lock operation in the thread memory:

1. 读--读锁 : 因为读锁允许同时拿锁,所以这里为线程不会互斥,都能快了的读取资源。
2. 读-写 | 写-读 锁:由于你存在了写操作,所有当线程拿到锁时,必须等线程释放锁才能由其他线程取锁。此处为互斥。
3. 写写锁 : 这里很容易理解为互斥。

Code test: https://blog.csdn.net/ligh_sqh/article/details/95178457 (forwarding)

Guess you like

Origin blog.csdn.net/qq_31142237/article/details/115143090