ReentrantReadWriteLock简介
-
分为读锁和写锁,读锁是共享锁(仅仅对需获取读锁的线程共享,如线程需要获取写锁则阻塞),写锁是排他锁,示例代码如下
public class MyReadWriteLock { private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(); public static void main(String[] args) { ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock(); ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock(); /* * 1、Thread-1加写锁,Thread-2阻塞 * 2、Thread-1加读锁,Thread-2需要获取读锁则Thread-2阻塞反之则能获取到锁 * 3、以上很好的证明了读锁属于共享锁,而写锁属于排它锁 * */ new Thread(()->{ method(writeLock); },"Thread-1").start(); new Thread(()->{ method(readLock); },"Thread-2").start(); } private static void method(Lock lock){ /*此处为了方便模拟读锁与写锁的共享性质和排他性质, *故意只加锁不释放锁 * */ lock.lock(); System.out.println(Thread.currentThread().getName()); } }