ReentrantReadWriteLock 读写锁。一种支持一写多读的同步锁,读写分离,可分别分配读锁、写锁;支持多次分配读锁,使多个读操作可以并发执行。
写-写:互斥,阻塞。读-写:互斥,读阻塞写、写阻塞读。读-读:不互斥、不阻塞。在读操作远远高于写操作的环境中,可在保障线程安全的情况下,提高运行效率。
public class Lock1 {
private int num;
// Lock lock1 = new ReentrantLock();
ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
// 读
Lock r = rwl.readLock();
// 写
Lock w = rwl.writeLock();
public Lock1() {
// TODO Auto-generated constructor stub
}
public int getNum() {
// 读操作并发执行
r.lock();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
r.unlock();
return num;
}
public void setNum(int num) {
w.lock();
try {
Thread.sleep(500);
this.num = num;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
w.unlock();
}
}
public class Test {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(20);
Lock1 l1 = new Lock1();
long start = System.currentTimeMillis();
for (int i = 0; i