ReentrantReadWriteLock 允许多个读操作同时进行,但是只允许一个写操作同时进行,在某些情况下,可以实现更高的并发性。
举个栗子:
public class ReadAndWriteLockTest {
static {
System.out.println("static "+Thread.currentThread().isDaemon());
}
public static void main(String[] args) {
//或者等所有的非守护线程结束后JVM终止运行
System.out.println(Thread.currentThread().isDaemon());
final Queue3 q3 = new Queue3();
for (int i=0; i<3; i++) {
new Thread(()->{
while(true){
q3.get();
}
}).start();
}
for (int i=0;i<3;i++) {
new Thread(()->{
while(true){
q3.put(new Random().nextInt(10000));
}
}).start();
}
}
}
class Queue3 {
/**共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据*/
private Object data = null;
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
public void get(){
//上读锁,其他线程只能读不能写
rwl.readLock().lock();
System.out.println(Thread.currentThread().getName() + " be ready to read data!");
try {
Thread.sleep((long)(Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放读锁
rwl.readLock().unlock();
}
System.out.println(Thread.currentThread().getName() + "have read data :" + data);
}
public void put(Object data){
//上写锁,不允许其他线程读也不允许写
rwl.writeLock().lock();
System.out.println(Thread.currentThread().getName() + " be ready to write data!");
try {
Thread.sleep((long)(Math.random()*1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + " have write data: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放写锁
rwl.writeLock().unlock();
}
}
}