1

我有一个多线程程序,我在其中创建了一个公允价值为 true 的 ReadWriteLock 实例。此应用程序已停止响应。

以下是我们基于线程转储的发现。一个线程获得了读锁,并在执行期间阻塞了 DB 操作。它很长时间没有释放锁。

除了上述线程之外,还有三个线程。一个线程正在等待获取写锁。而另外两个线程正在等待获取读锁。

问题是为什么两个线程都在等待读锁?是否因为公允价值为真并且请求写锁的线程早于请求读锁的两个线程而发生?如果请求写的线程来得更早,系统会阻塞请求读锁的线程吗?

4

1 回答 1

1

When you set a Java ReentrantReadWriteLock's fairness value to true, an attempt to get a read lock will block if there is a thread currently waiting to get the write lock, as you surmise. From the Javadoc:

"A thread that tries to acquire a fair read lock (non-reentrantly) will block if either the write lock is held, or there is a waiting writer thread."

In your situation, once the current read completes, the thread waiting to write will be allowed to write, then the other threads waiting to read will be allowed to read.

于 2015-03-20T18:40:39.187 回答