十五、讀寫鎖
阿新 • • 發佈:2018-12-24
讀寫分離 情況 imp style str .net get ring void
一、簡介
有時候我們對資源的修改操作非常地少,但是讀取的頻率卻很高。如果采用一般的互斥鎖,那麽大量的讀取操作也需要做等待。基於讀寫分離的思想,我們可以使用JDK的讀寫鎖來處理這種情況。
1)讀讀不互斥;
2)讀寫互斥。
3)寫寫互斥
JDK文檔地址:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/locks/ReentrantReadWriteLock.html
二、代碼示例
import java.util.concurrent.locks.ReentrantReadWriteLock; publicclass 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(); } }
十五、讀寫鎖