ReadWriteLock
JDK1.5提供读写分离锁,读写分离锁可以有效的减少锁竞争,以提升系统性能。比如:线程A1、A2、A3进行读操作,B1、B2、B3进行写操作,如果是重入锁或者内部锁,所有的读之间,读写之间和写写之间都是串行操作,如B1进行读取时,B2、B3需要等待锁。由于读操作并不对数据完整性造成破坏,因此这种等待是没有意义的。所以就有了读写锁。读写所允许多个线程同时读,但是写写操作和读写操作已让需要相互等待和持有锁的。
读写锁的约束情况:
public class ReadWriteDemo {
private static Lock reenlock = new ReentrantLock();
private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static Lock readLock = readWriteLock.readLock();
private static Lock writeLock = readWriteLock.writeLock();
private int value;
public Object handleRead(Lock lock) throws InterruptedException{
try {
lock.lock();
Thread.sleep(1000);
return value;
}finally{
lock.unlock();
}
}
public void handleWrite(Lock lock,int i) throws InterruptedException{
try {
lock.lock();
Thread.sleep(1000);
value = i;
}finally{
lock.unlock();
}
}
public static void main(String args[]) throws InterruptedException {
final ReadWriteDemo demo = new ReadWriteDemo();
Runnable readRunnable = new Runnable(){
public void run() {
try {
//demo.handleRead(readLock);
demo.handleRead(reenlock);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable writeRunnable = new Runnable(){
public void run() {
try {
//demo.handleWrite(writeLock,new Random().nextInt());
demo.handleWrite(reenlock,new Random().nextInt());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
//System.out.println(System.currentTimeMillis());
for(int i=0;i<18;i++){
Thread t = new Thread(readRunnable);
t.start();
//t.join();
}
for(int i=0;i<2;i++){
Thread t = new Thread(writeRunnable);
t.start();
//t.join();
}
//System.out.println(System.currentTimeMillis());
}
}