用的比较少, 做一个参考. 原文在[url=http://examples.javacodegeeks.com/core-java/util/concurrent/reentrant-readwritelock-example-of-value-calculator]这里[/url]
public class Calculator {
private int calculatedValue;
private int value;
private ReadWriteLock lock = new ReentrantReadWriteLock();
public void calculate(int value) {
lock.writeLock().lock();
try {
this.value = value;
this.calculatedValue = doMySlowCalculation(value);
} finally {
lock.writeLock().unlock();
}
}
public int getCalculatedValue() {
lock.readLock().lock();
try {
return calculatedValue;
} finally {
lock.readLock().unlock();
}
}
public int getValue() {
lock.readLock().lock();
try {
return value;
} finally {
lock.readLock().unlock();
}
}
}