ReadWriteLock接口
什么是ReadWriteLock?
JDK1.8官方文档这样解释:ReadWriteLock维护一对关联的locks ,一个用于只读操作,一个用于写入。 read lock可以由多个阅读器线程同时进行,只要没有作者。write lock是独家的。
意思就是可以实现多个读线程同时读取数据,但是写线程需要互斥执行。
读|写 、写|写 需要互斥
读|读 不需要互斥
注意:读写锁允许访问共享数据时的并发性高于互斥锁所允许的并发性
我们再使用读写锁时需要使用其实现类:ReentrantReadWriteLock
ReentrantReadWriteLock类
public class ReadWriteLockDemo {
public static void main(String[] args) {
//共享资源
Res res = new Res();
//写入(互斥)
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Runnable runnable1 = new Runnable() {
@Override
public void run() {
lock.writeLock().lock();//获得一把写入锁,该锁是互斥的
try{
Thread.sleep(100);
int i = new Random().nextInt(1000);
res.setNum(i);
System.out.println(Thread.currentThread().getName()+"写入了:"+i);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();//对写入锁解锁
}
}
};
//读取(共享锁)
Runnable runnable2 = new Runnable() {
@Override
public void run() {
//上锁
lock.readLock().lock();//获得一把读取锁,该锁是共享的
try {
Thread.sleep(100);
int num = res.getNum();
System.out.println(Thread.currentThread().getName()+"读取了:"+num);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.readLock().unlock();//对读取锁解锁
}
}
};
//创建线程
for (int i = 0; i < 10; i++) {
new Thread(runnable1).start();
}
for (int i = 0; i < 100; i++) {
new Thread(runnable2).start();
}
}
}
public class Res {
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}