锁提供的最显著的改进之一是 ReadWriteLock 接口和 ReentrantReadWriteLock 类。 此类有2个锁,一个供读操作,一个供写操作:
数据类 (PricesInfo)
private double price1; private double price2;
private ReadWriteLock lock;
public PricesInfo() { price1 = 1.0; price2 = 2.0; lock = new ReentrantReadWriteLock(); }
public double getPrice1() { lock.readLock().lock(); double value = price1; lock.readLock().unlock(); return value; }
public void setPrices(double price1, double price2) { lock.writeLock().lock(); this.price1 = price1; this.price2 = price2; lock.writeLock().unlock(); }
线程类 : Reader
private PricesInfo pricesInfo; public Reader(PricesInfo pricesInfo) { this.pricesInfo = pricesInfo; }
for (int i = 0; i < 10; i++) { System.out.printf("%s: Price 1: %f, Price 2: %f\n", Thread.currentThread().getName(), pricesInfo.getPrice1(), pricesInfo.getPrice2()); }
线程类 : Writer
private PricesInfo pricesInfo; public Writer(PricesInfo pricesInfo) { this.pricesInfo = pricesInfo; }
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(); } }
控制类 : Main
ReentrantReadWriteLock 有2个锁,一个给读操作,一个给写操作。
确保这些锁的正确使用、按它们的设计目的使用是程序员的责任。拿到读锁时,不能修改变量的值。否则会有数据不一致的错误。