公众号merlinsea
特性:写写互斥,读写互斥,读读共享
锁降级:写线程在获取写锁以后,完成写操作以后可以获取读锁同时释放写锁,即实现了锁降级。
/** * ReentrantReadWriteLockDemo */ public class ReentrantReadWriteLockDemo { private int i = 0; private int j = 0; private ReadWriteLock lock = new ReentrantReadWriteLock(); Lock readLock = lock.readLock(); // 获取读锁 Lock writeLock = lock.writeLock(); // 获取写锁 // 由于out是执行输出操作,不涉及修改操作,因此允许多个线程同时执行out, // 故使用读锁进行lock public void out(){ readLock.lock(); try { System.out.println(Thread.currentThread().getName()+"i的值====》"+i + "j的值====》"+j); }finally { readLock.unlock(); } } // 由于inCreate是写数据操作,因此应该互斥访问,使用写锁进行lock 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(); } }
vip算法班永久学习班: 800元/人
周一、周三、周五:8:30-9:30,周六、周日:10:30-11:30
报名方式:通过公众号导航栏的刷题群即可联系到我的微信号
vip算法班详情链接如下:
奔跑的小梁,公众号:梁霖编程工具库算法训练营快来参加吧~