读写锁(ReentrantReadWriteLock)

读写锁:核心思想实现读写分离,高并发下特别适合 读多写少的场景。

synchronized关键字和ReentrantLock 同一时间只能有一个线程进行访问被锁定的代码,读写锁的机制则不是,本质上分为两把锁,读锁和写锁,在读锁情况下,多个线程可以并发访问资源,只有当是写锁时只能一个一个的顺序执行。

口诀:读读共享,写写互斥,读写互斥。

private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); 
private ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock(); 
private ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock(); 
public void read() { 
    try { 
      readLock.lock(); 
      System.out.println("当前线程:" + Thread.currentThread().getName() + "进入..."); 
      Thread.sleep(3000); 
      System.out.println("当前线程:" + Thread.currentThread().getName() + "退出..."); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } finally { 
      readLock.unlock(); 
    } 
} 
public void write() { 
     try { 
        writeLock.lock(); 
        System.out.println("当前线程:" + Thread.currentThread().getName() + "进入..."); 
        Thread.sleep(3000); 
        System.out.println("当前线程:" + Thread.currentThread().getName() + "退出..."); 
     } catch (Exception e) { 
        e.printStackTrace();
     } finally {
       writeLock.unlock();
     } 
}

你可能感兴趣的:(读写锁(ReentrantReadWriteLock))