1. ReadWriteLock: The read operation and the write operation thread run together to improve the efficiency of the same operation.
2. Test code:
public class T_ReadWriteLock {
static Lock lock = new ReentrantLock();
static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
static Lock readLock = readWriteLock.readLock();
static Lock writeLock = readWriteLock.writeLock();
public static void read(Lock lock){
try {
lock.lock();
//读需要1秒
Thread.sleep(1000);
System.out.println("读完毕!");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void write(Lock lock) {
try {
lock.lock();
//写需要2秒
Thread.sleep(2000);
System.out.println("写完毕!");
}catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
// Runnable read = ()->read(lock); //使用正常锁
// Runnable write = ()->write(lock);
Runnable read = ()->read(readLock);
Runnable write = ()->write(writeLock);
for (int i=0; i<18; i++) new Thread(read).start();
for (int i=0; i<2; i++) new Thread(write).start();
}
}