讀寫鎖允許同一時刻被多個線程訪問,但是在寫線程訪問時熏版,所有的讀線程和其他的寫線程都會被阻塞 纷责。比如線程A1,A2撼短,A3進行寫操作再膳,線程B1,B2曲横,B3進行讀操作喂柒,如果使用重入鎖或者內(nèi)部鎖不瓶,所有讀之間,讀寫之間灾杰,寫寫之間都是串行操作蚊丐,而使用讀寫鎖的話,允許多個線程同時讀艳吠。
讀寫鎖的使用:
public class ReadWriteLockDemo {
private static ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
private static Lock readLock=readWriteLock.readLock();
private static Lock writeLock=readWriteLock.writeLock();
private int value;
public int 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();
}
}
}