ReentrantReadWriteLock读写锁
读写锁可以将读写分离,有效的减少锁竞争。通过读写锁达到读-读不互斥。读-写以及写-写互斥。如果读的次数多,写的次数少,可以发挥很好的功效。
public class ReenterReadWriteLockTest {
private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
private static final Lock readLock = readWriteLock.readLock();
private static final Lock writeLock = readWriteLock.writeLock();
public static void main(String[] args) {
Thread readT = new Thread(new Runnable() {
@Override
public void run() {
try {
readLock.lock();
//读操作
} finally {
readLock.unlock();
}
}
});
Thread writeT = new Thread(new Runnable() {
@Override
public void run() {
try {
writeLock.lock();
//写操作
} finally {
writeLock.unlock();
}
}
});
readT.start();
writeT.start();
}
}