ReentrantReadWriteLock类,该类实现了锁的读写分离
里面有两个内部类WriteLock、ReadLock
我们都知道在并发编程过程中,只有加锁才能保证代码的有条不紊的进行,但不是每段代码都要进行加锁操作,比如在读取数据操作的一类代码中就不要加锁,从而提升程序的性能
而该ReentrantReadWriteLock类中就实现了锁的读写分离
该类的特点是
1、对数据的读取的时候,拿到readLock进行操作,如果要对数据进行修改时,拿到相应的WriteLock锁,才能对其修改,如果有其它线程拿到readLock锁正在进行读取操作的时候,这时再去获取WriteLock锁时,程序会一直阻塞下去,直到其它线程全部释放readLock锁
2、readLock锁可以被多个线程同时占用,因此readLock锁是共享锁
3、writeLock锁,只能同时被一个线程占用,其它线程要再去获取writeLock锁时,只能等待该线程释放writeLock锁
注意:在操作的过程中,记得释放
private static final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);
private static final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
private static final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock()
private static final ReadLockTest test = new ReadLockTest();
private static volatile int num = 0;
public void writePlus() throws InterruptedException {
System.out.println(Thread.currentThread().getName()+"开始加一");
System.out.println("上次的值是 "+num+" 加完之后 "+ ++num);
System.out.println(Thread.currentThread().getName()+"加一结束,开始睡2秒");
Thread.sleep(2000);
}
public static void write() {
for (int i = 0; i < 2; i++) {
new Thread(() -> {