概述ReentrantReadWriteLock维护了一对相关的锁,它们分别是共享readLock和独占writeLock。关于共享读锁和排他写锁的概念其实很好理解。所谓共享读锁就是一个线程读的时候,其它线程也可以来读(共享),但是不能来写。排他写锁是指一个线程在写的时候,其它线程不能来写或读(排他)。除了这个特点之外,ReentrantReadWriteLock还有一个特点就是可重入的。它和ReentrantLock一样都是支持Condition的。而且ReentrantReadWerite还支持锁降级,即允许将写锁降级为读锁。简单使用最最基础的用法如下:ReentrantReadWriteLock lock=new ReentrantReadWriteLock(); public void read(){ lock.readLock().lock(); //需要加读锁的操作 lock.readLock().unlock(); } public void write(){ lock.writeLock().lock(); //需要加写锁的操作 lock.writeLock().unlock(); }ReentrantReadWriteLock无非就是这几种情况,读读共享,写写互斥,读写互斥,写读互斥。下面我们就以这个最基础的用法,来分析一下其内部的原理源码分析继承体系共享读锁的实现原理分析#lock方法#首先进入调用具体的实现public void lock() { sync.acquireShared(1); }然后调用了这个方法public final void acquireShared(int arg) { if (tryAcquireShared(arg) 0) doAcquireShared(arg); }其中int tryAcquireShared(int unused)的具体实现如下:protected final int tryAcquireShared(int unused) { /* * Walkthrough: * 1. If write lock held by another thread, fail. * 2. Otherwise, this thread is eligible for * lock wrt state, so ask if it should block * because of queue policy. If not, try * to grant by CASing state and updating count. * Note that step does not check for reentrant * acquires, which is postponed to full version * to avoid having to check hold count in * the more typical non-reentrant case. * 3. If step 2 fails either because thread * apparently not eligible or CAS fails or count * saturated, chain to version with full retry loop. */ Thread current = Thread.currentThread(); int c = getState(); //持有写锁的线程可以获取读锁,如果获取锁的线程不是当前线程,则返回-1 if (exclusiveCount(c) !