1. 访问情况
读-读不互斥:读读之间不阻塞。
读-写互斥:读阻塞写,写也会阻塞读。
写-写互斥:写写阻塞。
2.主要接口
private static ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
private static Lock readLock = readWriteLock.readLock();
private static Lock writeLock = readWriteLock.writeLock();
3. 程序实例
package com.john.learn.high.concurent.ch03;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockDemo {
private int value;
private static ReentrantReadWriteLock ReadWriteLock = new ReentrantReadWriteLock();
private static Lock Lock = new ReentrantLock();
private Lock readLock = null;
private Lock writeLock = null;
public ReadWriteLockDemo(Lock readLock, Lock writeLock) {
this.readLock = readLock;
this.writeLock = writeLock;
}
public ReadWriteLockDemo(ReentrantReadWriteLock readWriteLock) {
this.readLock = readWriteLock.readLock();
this.writeLock = readWriteLock.writeLock();
}
public Object read() throws InterruptedException {
try {
readLock.lock();
Thread.sleep(100);
return value;
} finally {
readLock.unlock();
}
}
public void write(int value) throws InterruptedException {
try {
writeLock.lock();
Thread.sleep(100);
this.value = value;
} finally {
writeLock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[500];
doTestCost("ReentrantLock", threads, new ReadWriteLockDemo(Lock, Lock));
doTestCost("ReentrantReadWriteLock", threads, new ReadWriteLockDemo(ReadWriteLock));
}
private static void doTestCost(String targetName, Thread[] threads, final ReadWriteLockDemo readWriteLockDemo)
throws InterruptedException {
for (int i = 0; i < threads.length; i++) {
if (i < threads.length - 2) {
threads[i] = new Thread() {
public void run() {
try {
readWriteLockDemo.read();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
};
continue;
}
threads[i] = new Thread() {
public void run() {
try {
readWriteLockDemo.write(new Random().nextInt());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
long start = System.currentTimeMillis();
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(targetName + " cost is " + (System.currentTimeMillis() - start) +" .");
}
}
使用读写锁 和 重用锁的性能对比:498个Thread 读 2个Thread 写,每一个操作耗时 100 毫秒
读写锁比重用锁快100多倍。