- 特性:写写互斥、读写互斥、读读共享
- 锁降级:写线程获取写入锁后可以获取读取锁,然后释放写入锁,这样就从写入锁变成了读取锁,从而实现锁降级的特性。
-
public class ReentrantReadWriteLockDemo { private int i = 0; private int j = 0; private ReadWriteLock lock = new ReentrantReadWriteLock(); Lock readLock = lock.readLock(); Lock writeLock = lock.writeLock(); public void out(){ readLock.lock(); try { System.out.println(Thread.currentThread().getName()+"i的值====》"+i + "j的值====》"+j); }finally { readLock.unlock(); } } public void inCreate() { writeLock.lock(); try { i++; Thread.sleep(500L); j++; } catch (InterruptedException e) { e.printStackTrace(); }finally { writeLock.unlock(); } } public static void main(String[] args) { ReentrantReadWriteLockDemo reentrantReadWriteLockDemo = new ReentrantReadWriteLockDemo(); // for (int i = 0; i < 3; i++) { // new Thread(()->{ // reentrantReadWriteLockDemo.inCreate(); // reentrantReadWriteLockDemo.out(); // }).start(); // } // new Thread(()->{ // reentrantReadWriteLockDemo.out(); // },"读线程").start(); // new Thread(()->{ // reentrantReadWriteLockDemo.inCreate(); // },"写线程").start(); new Thread(()->{ reentrantReadWriteLockDemo.out(); },"读线程1").start(); new Thread(()->{ reentrantReadWriteLockDemo.out(); },"读线程2").start(); } }
读写锁特性及ReentrantReadWriteLock的使用
最新推荐文章于 2022-08-15 23:12:53 发布