1. Concept
A reentrant read-write lock. The read-write lock maintains a ReadLock and a WriteLock, and the underlying layer is AQS. , but AQS has only one state quantity. How to control reading and writing at the same time? The high 16 bits of state (int) are used here to represent the read status, the low 16 bits represent writing, and the high 16 bits represent the number of threads to obtain the read lock. ,The lower 16 bits represent the reentrant number of the ,write lock.
2. Principle
Use CAS AQS queue to implement. It supports fair locks and unfair locks. The implementation of both is similar to
3, example
public class ReentrantDemo implements Runnable { Lock lock = new ReentrantLock(); @Override public void run() { set(); } public void set() { try { lock.lock(); System.out.println("set 方法"); get(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock();// 必须在finally中释放 } } public void get() { try { lock.lock(); System.out.println("get 方法"); } 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 detailed content of Java test example to analyze the reentrant characteristics of ReentrantLock. For more information, please follow other related articles on the PHP Chinese website!