ReadWriteLock 可以实现的是可以多线程读,然后写线程不与读线程冲突
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class TestReadWriteLock {
static Lock lock = new ReentrantLock();// 这里引入ReentrantLock()是为了比较读锁和写锁的区别,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();
Thread.sleep(1000);
System.out.println("read is over!");
}catch (InterruptedException e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void write(Lock lock){
try {
lock.lock();
Thread.sleep(1000);
System.out.println("write is over!");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
// Runnable readR = ()->read(lock);
// Runnable writeR = ()->write(lock,new Random().nextInt());
Runnable readR = ()->read(readLock);
Runnable writeR = ()->write(writeLock);
for (int i = 0; i <10 ; i++) {
new Thread(readR).start();
}
for (int i = 0; i < 2; i++) {
new Thread(writeR).start();
}
}
}
输出结果:
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over! //这10个读是一瞬间完成的
write is over!
write is over!
当然为了对比,采用另一个锁,放开这段注释
// Runnable readR = ()->read(lock);
// Runnable writeR = ()->write(lock,new Random().nextInt());
输出结果如下:
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over!
read is over! //这10个读是1秒输出打印一次“write is over”
write is over!
write is over!