一、简介
有时候我们对资源的修改操作非常地少,但是读取的频率却很高。如果采用一般的互斥锁,那么大量的读取操作也需要做等待。基于读写分离的思想,我们可以使用JDK的读写锁来处理这种情况。
1)读读不互斥;
2)读写互斥。
3)写写互斥
二、代码示例
import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockDemo { private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); private static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); private static void read() { for (int i = 0; i < 2; i++) { int finalI = i; new Thread(() -> { readLock.lock(); try { System.out.println("get read lock i=" + finalI); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } readLock.unlock(); }).start(); } } public static void write() { new Thread(() -> { writeLock.lock(); System.out.println("get write lock"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } writeLock.unlock(); }).start(); } public static void main(String[] args) throws InterruptedException { write(); read(); } }
原文地址:https://www.cnblogs.com/lay2017/p/10166536.html
时间: 2024-10-10 20:52:27