The operating environment of this tutorial: windows7 system, java10 version, DELL G3 computer.
1. Concept
A reentrant read-write lock . The read-write lock maintains a ReadLock and a WriteLock internally. The bottom layer is still AQS, but AQS only has one state state quantity. How to control reading and writing at the same time? The high 16 of state (int) is used here. The bit represents the read status, the low 16 bits represent writing, the high 16 bits represent the number of threads acquiring the read lock, and the low 16 bits represent the reentrant number of the write lock.
2. Principle
Implemented using CAS+AQS queue. It supports fair locks and unfair locks, and the implementation of the two is similar
3. Examples
public class ReentrantDemo implements Runnable { Lock lock = new ReentrantLock(); @Override public void run() { set(); } public void set() { try { lock.lock(); System.out.println("set method"); get(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock();//Must be released in finally } } public void get() { try { lock.lock(); System.out.println("get method"); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) { ReentrantDemo reentrantDemo = new ReentrantDemo(); new Thread(reentrantDemo).start(); } }
The above is the reentrant test of java ReentrantLock. I believe that after reading the entire article, everyone will be able to initially understand the use of ReentrantLock, and you can also expand the related content of reentrant lock after class.