首页 > 代码库 > ReadWriteLock 读写锁(读书笔记)
ReadWriteLock 读写锁(读书笔记)
读写分离锁可以有效的帮助减少锁的竞争,提升系统的效率,
- 读-读不互斥 读读之间不阻塞
- 读-写互斥 读阻塞写,写也会阻塞读
- 写-写互斥 写写阻塞
在系统中,读操作次数远远大于写操作,则读写锁就可以发挥最大的功效,提升系统的性能.
public class ReadWriteLockDemo { private static Lock lock = new ReentrantLock(); private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private static Lock readLock = readWriteLock.readLock(); private static Lock writeLock = readWriteLock.writeLock(); private int value; public Object handleRead(Lock lock) throws InterruptedException { try { lock.lock(); Thread.sleep(1000);//模拟读操作 return value; } finally { lock.unlock(); } } public void handleWrite(Lock lock, int index) throws InterruptedException { try { lock.lock(); Thread.sleep(1000); this.value =http://www.mamicode.com/ index; } finally { lock.unlock(); } } public static void main(String[] args) { final ReadWriteLockDemo demo = new ReadWriteLockDemo(); Runnable readRunnable = () -> { try { Object o = demo.handleRead(readLock);//读写锁 // Object o1 = demo.handleRead(lock);//普通锁 } catch (InterruptedException e) { e.printStackTrace(); } }; Runnable writeRunnable = () -> { try { demo.handleWrite(writeLock, new Random().nextInt());//读写锁 //demo.handleWrite(lock, new Random().nextInt());//普通锁 } catch (InterruptedException e) { e.printStackTrace(); } }; for (int i = 0; i < 18; i++) { new Thread(readRunnable).start(); } for (int i = 18; i < 20; i++) { new Thread(writeRunnable).start(); } } }
我们分别使用重入锁和读写锁,耗时有明显的减少!
ReadWriteLock 读写锁(读书笔记)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。