这个输出结果就是我根据你写的代码输出的。其中线程3为什么在线程1、2读的时候也能进行写呢?
public class CinemaReadWriteLock {
private static final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
/**
* 读锁
*/
private static final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
/**
* 写锁
*/
private static final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
/**
* 读锁:只能多读
*/
public static void read() {
readLock.lock();
try {
System.out.println(Thread.currentThread().getName() + ":获取到了读锁");
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readLock.unlock();
System.out.println(Thread.currentThread().getName() + ":释放了读锁");
}
}
/**
* 写锁:只能一写
*/
public static void write() {
writeLock.lock();
try {
System.out.println(Thread.currentThread().getName() + ":获取到了写锁");
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + ":释放了写锁");
writeLock.unlock();
}
}
public static void main(String[] args) {
new Thread(CinemaReadWriteLock::read,"1").start();
new Thread(CinemaReadWriteLock::read,"2").start();
new Thread(CinemaReadWriteLock::write,"3").start();
new Thread(CinemaReadWriteLock::write,"4").start();
}
}
我用的是JDK 11,发现这个现象与JDK 8不一样。