What is the use of the read lock in the ReentrantReadWriteLock read-write lock in Java?

Reading and reading are not mutually exclusive, reading and writing are mutually exclusive, writing and writing are mutually exclusive

If the read lock is added, other threads will be blocked if they want to add a write lock.

Prevent other threads from writing when reading, and allow other threads to read when reading

Question: After adding a read lock, other threads can add a write lock to make changes. In addition, if I don’t add a read lock, can all threads be read? Ask the boss to explain in detail.

Answer:
A thread owns the write lock of object A. Before the write lock is released, other threads cannot obtain the read lock and write lock of A. Therefore, other threads cannot read or write at this time;
a thread owns the read lock of object A and is releasing The other threads can obtain the read lock of A but cannot obtain the write lock of A, so other threads can read but not write at this time.
Without the read lock, other threads can read, but can also write, then the data may be inconsistent

The first write lock can obtain the read lock, and the first read lock cannot obtain the write lock. Simply put, the lock can be downgraded but not upgraded.

Reference:
https://www.nowcoder.com/discuss/37157?type=0&order=0&pos=15&page=1

Guess you like

Origin blog.csdn.net/Brave_heart4pzj/article/details/115047091