使用read/write锁同步数据
在同步机制中,一个显著的改进就是提供了ReadWriteLock接口和其实现类ReentrantReadWriteLock,该类有一对互斥锁(mutual exclusion lock),一个是read lock,一个是write lock,在同一时刻可以有多个读线程或者在同一时刻只能有一个写线程;当一个写线程正在执行,所有的读线程都将被阻塞,因为读Lock和写Lock是一对互斥的锁;
ReadWriteLock接口中哦那个有两个方法:
- Lock readLock();
- Lock writeLock();
ReentrantReadWriteLock是该接口的唯一实现类;
下面一个例子是读写一个价格信息
动手实现
(1)创建价格信息类
public class PricesInfo {
private double priceA;
private double priceB;
private ReadWriteLock lock=new ReentrantReadWriteLock();
public PricesInfo() {
this(1.0, 2.0);
}
public PricesInfo(double priceA, double priceB) {
this.priceA = priceA;
this.priceB = priceB;
}
public double getPriceA() {
lock.readLock().lock();
System.out.printf("%s: PriceA readLock: lock\n",Thread.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
double value=priceA;
System.out.printf("%s: PriceA readLock: unlock\n",Thread.currentThread().getName());
lock.readLock().unlock();
return value;
}
public double getPriceB() {
lock.readLock().lock();
double value=priceB;
lock.readLock().unlock();
return value;
}
public void setPrices(double priceA, double priceB) {
lock.writeLock().lock();
System.out.printf("%s :Writer locked.\n",Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.priceA=priceA;
this.priceB=priceB;
lock.writeLock().unlock();
System.out.printf("%s :Writer unlock.\n", Thread.currentThread().getName());
}
}
(2)创建读线程
public class Reader implements Runnable{
private PricesInfo pricesInfo;
public Reader(PricesInfo pricesInfo) {
this.pricesInfo = pricesInfo;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.printf("%s: Price B: %f\n",
Thread.currentThread().getName(),pricesInfo.getPriceB());
System.out.printf("%s: Price A: %f\n",
Thread.currentThread().getName(),pricesInfo.getPriceA());
}
}
}
(3)创建写线程
public class Writer implements Runnable {
private PricesInfo pricesInfo;
public Writer(PricesInfo pricesInfo) {
this.pricesInfo = pricesInfo;
}
@Override
public void run() {
for (int i=0; i<3; i++) {
System.out.printf("Writer: Attempt to modify the prices.\n");
pricesInfo.setPrices(Math.random() * 10, Math.random() * 8);
System.out.printf("Writer: Prices have been modified.\n");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
通过观察输出可以看出:
- 当没有出现写线程时,多个读线程之间互不相干,正常读取;
- 只有当读线程都释放了锁,写线程才能执行,并且同一时刻只能执行一个;
- 当写线程执行时,读线程都将阻塞;
要点
ReadWriteLock包含一对互斥锁,当Read Lock被线程占有时,Write Lock被阻塞;反之亦然;读线程可以有多个;