ReentrantReadWriteLock 写锁未释放也能获取到读锁?
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @Description:
* @Author: reed
*/
public class ReadWriteLockDemo {
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private static Lock writeLock = lock.writeLock();
private static Lock readLock = lock.readLock();
private static int[] arr = new int[10];
public static void main(String[] args) {
Thread t1 = new Thread(new WriteTask());
Thread t2 = new Thread(new ReadTask());
Thread t3 = new Thread(new ReadTask());
t1.start();
t2.start();
t3.start();
}
static class WriteTask implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
writeLock.lock();
try {
int index = (int) (Math.random() * 10);
arr[index] = (int) (Math.random() * 100);
System.out.println("+持有写锁, 将 arr[" + index + "] 修改为 " + arr[index] + ", " + Thread.currentThread()
.getName());
} finally {
writeLock.unlock();
System.out.println("-写锁释放" + ", " + Thread.currentThread()
.getName());
}
}
}
}
static class ReadTask implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
readLock.lock();
try {
int index = (int) (Math.random() * 10);
System.out.println("+持有读锁,下标 " + index + ",值 " + arr[index] + ", " + Thread.currentThread()
.getName());
} finally {
readLock.unlock();
System.out.println("-读锁释放" + ", " + Thread.currentThread()
.getName());
}
}
}
}
}
其中一次运行结果:
写锁(Thread-0)还没释放前为什么能获取到读锁吗?获取读锁的线程(Thread-2, 与持有写锁的线程不同)不应该是阻塞的吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的想法是没错的。
执行的语句可能是这样的:
0线程持有写锁
0线程释放写锁
1线程获取读锁
1线程获取读锁
2线程获取读锁
2线程获取读锁
(12获取释放的打印略过)
0线程打印释放写锁
也就是说,读锁执行完
writeLock.unlock();
,读线程就可以获取锁,此时写线程还没执行打印语句,就造成了上面的运行情况