Java多线程基础总结八:ReentrantReadWriteLock

[size=medium]
说到ReentrantReadWriteLock,首先要做的是与ReentrantLock划清界限。它和后者都是单独的实现,彼此之间没有继承或实现的关系。 然后就是总结这个锁机制的特性了:
[list]
[*](a).重入方面其内部的WriteLock可以获取ReadLock,但是反过来ReadLock想要获得WriteLock则永远都不要想。
[*](b).WriteLock可以降级为ReadLock,顺序是:先获得WriteLock再获得ReadLock,然后释放WriteLock,这时候线程将保持Readlock的持 有。反过来ReadLock想要升级为WriteLock则不可能,为什么?参看(a),呵呵.
[*](c).ReadLock可以被多个线程持有并且在作用时排斥任何的WriteLock,而WriteLock则是完全的互斥。这一特性最为重要,因为对于高 读取频率而相对较低写入的数据结构,使用此类锁同步机制则可以提高并发量。
[*](d).不管是ReadLock还是WriteLock都支持Interrupt,语义与ReentrantLock一致。
[*](e).WriteLock支持Condition并且与ReentrantLock语义一致,而ReadLock则不能使用Condition,否则抛出 UnsupportedOperationException异常。
[*]以上就是比较重要的,或者衡量是否使用ReentrantReadWriteLock的基础了。下面还是写个小例子说明部分内容:
[/list]
[/size]

package thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockSample {

public static void main(String[] args) {
testReadLock();
// testWriteLock();
}

public static void testReadLock() {
final ReadWriteLockSampleSupport support = new ReadWriteLockSampleSupport();
support.initCache();

Runnable runnable = new Runnable() {
public void run() {
support.get("test");
}
};

new Thread(runnable).start();
new Thread(runnable).start();

new Thread(new Runnable() {
public void run() {
support.put("test", "test");
}
}).start();
}

public static void testWriteLock() {
final ReadWriteLockSampleSupport support = new ReadWriteLockSampleSupport();
support.initCache();

new Thread(new Runnable() {
public void run() {
support.put("key1", "value1");
}
}).start();

new Thread(new Runnable() {
public void run() {
support.put("key2", "value2");
}
}).start();

new Thread(new Runnable() {
public void run() {
support.get("key1");
}
}).start();
}
}

class ReadWriteLockSampleSupport {
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();

private volatile boolean completed;
private Map cache;

public void initCache() {
readLock.lock();
if (!completed) {
// Must release read lock before acquiring write lock
readLock.unlock(); // (1)
writeLock.lock(); // (2)
if (!completed) {
cache = new HashMap(32);
completed = true;
}
// Downgrade by acquiring read lock before releasing write lock
readLock.lock(); // (3)
writeLock.unlock(); // (4) Unlock write, still hold read
}

System.out.println("empty? " + cache.isEmpty());
readLock.unlock();
}

public String get(String key) {
readLock.lock();
System.out.println(Thread.currentThread().getName() + " read.");
startTheCountdown();
try {
return cache.get(key);
} finally {
readLock.unlock();
}
}

public String put(String key, String value) {
writeLock.lock();
System.out.println(Thread.currentThread().getName() + " write.");
startTheCountdown();
try {
return cache.put(key, value);
} finally {
writeLock.unlock();
}
}

/**
* A simple countdown,it will stop after about 5s.
*/
public void startTheCountdown() {
long currentTime = System.currentTimeMillis();
for (;;) {
long diff = System.currentTimeMillis() - currentTime;
if (diff > 5000) {
break;
}
}
}
}

[size=medium]
这个例子改造自JDK的API提供的示例,其中ReadWriteLockSampleSupport辅助类负责维护一个Map,当然前提是这个Map大部分的多线程 下都是读取,只有很少的比例是多线程竞争修改Map的值。其中的initCache()简单的说明了特性(a),(b).在这个方法中如果把注释(1)和(2) 处的代码调换位置,就会发现轻而易举的死锁了,当然是因为特性(1)的作用了。而注释(3),(4)处的代码位置则再次证明了特性 (a),并 且有力的反映了特性(b)--WriteLock在cache初始化完毕之后,降级为ReadLock。另外get(),put()方法在线程获取锁之后会在方法中呆上近 5s的时间。
ReentrantReadWriteLockSample中的两个静态测试方法则分别测试了ReadLock和WriteLock的排斥性。testReadLock()中,开启三个线程 ,前两者试图获取ReadLock而后者去获取WriteLock。执行结果可以看到:ReadWriteLockSampleSupport的get()方法中的打印结果在前两个 线程中几乎同时显示,而put()中的打印结果则要等上近5s。这就说明了,ReadLock可以多线程持有并且排斥WriteLock的持有线程。 testWriteLock()中,也开启三个线程。前两个是去获取WriteLock,最后一个获取ReadLock。执行的结果是三个打印结果都有近5s的间隔时 间,这说明了WriteLock是独占的,比较独!
[/size]

ref:http://www.bianceng.cn/Programming/Java/201206/34156.htm

你可能感兴趣的:(多线程)