首页 > 代码库 > 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 读写锁(读书笔记)