ReadWriteLock是JDK1.5中提供的读写分离锁。读写分离可以有效的减少锁竞争,以此来高系统的性能。
读写锁允许多个线程同时读,但是考虑到数据完整性,写写操作,和读写操作依然是需要相互等待和持有锁的。如下图:
如果在系统中,读操作次数远远大于写操作,则读写锁就可以发挥最大的功效了。上代码:
package com.example.thread;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by mazhenhua on 2017/3/8.
*/
public class ReadWriteLockDemo {
private static Lock lock = new ReentrantLock();
private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
private static Lock readLock = reentrantReadWriteLock.readLock();
private static Lock writeLock = reentrantReadWriteLock.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 index) throws InterruptedException{
try {
lock.lock();
Thread.sleep(1000);
value = index;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
final ReadWriteLockDemo demo = new ReadWriteLockDemo();
Runnable readRunable = new Runnable() {
@Override
public void run() {
try {
demo.handleRead(readLock);
//demo.handleRead(lock);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
final Runnable writeRunable = new Runnable() {
@Override
public void run() {
try {
demo.handleWrite(writeLock, new Random().nextInt());
//demo.handleWrite(lock, new Random().nextInt());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for (int i = 0; i < 18; i ++){
new Thread(readRunable).start();
}
for (int i = 18; i < 20; i ++){
new Thread(writeRunable).start();
}
}
}
这段代码很快就执行完了,如果把注掉的地方替换一下,可能就要执行好长时间了。