ReadWriteLock 读写锁(读书笔记)

Posted Darcy_wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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 读写锁(读书笔记)的主要内容,如果未能解决你的问题,请参考以下文章

ReadWriteLock: 读写锁

java多线程 -- ReadWriteLock 读写锁

java多线程ReadWriteLock读写锁

读写锁之ReadWriteLock

Java——多线程高并发系列之ReadWriteLock读写锁

Java——多线程高并发系列之ReadWriteLock读写锁