最近在研究jdk的锁机制,reentrantreadwritelock实现了读写锁分离机制,其中读锁可以被多个线程重入,写锁是独占的,并且在写锁开启的时候,读取操作进入阻塞队列。这里我做了一个测试,来观察在公平与非公平模式下读写锁互相如何抢占资源,下面附上测试代码
package test.readWriteLock;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by Jeff on 2016/6/14.10:20
*/
public class Client {
public static void main(String args []){
final Resource rs = new Resource("Jeff");
//这里设置抢占模式,公平或非公平
final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(false);
final Lock readLock = readWriteLock.readLock();
final Lock writeLock = readWriteLock.writeLock();
final Random r = new Random();
//写入线程
for(int i =0;i<10;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
writeLock.lock();
rs.setName(rs.getName() + "-" + Thread.currentThread().getName());
System.out.println("线程" + Thread.currentThread().getName() + "获取到写入锁,将资源写为:" + rs.getName());
System.out.println("queueLength:"+readWriteLock.getQueueLength()+
",readholdsCount:"+readWriteLock.getReadHoldCount()+
",readLockCount:"+readWriteLock.getReadLockCount()+
",writeHoldCount:"+readWriteLock.getWriteHoldCount()+
",writeLockCount"+readWriteLock.getReadLockCount());
Thread.sleep(r.nextInt(10) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}
}).start();
}
System.out.println("启动读线程");
//读取线程启动
for(int i=0;i<10;i++){
new Thread(
new Runnable() {
@Override