/** * Returns true if the current thread, when trying to acquire * the read lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. * 如果当前线程在尝试获取读锁时阻塞,并且由于策略原因无法超过其他等待的线程, * 因此有资格阻塞读锁,则返回true。 */ abstractbooleanreaderShouldBlock();
/** * Returns true if the current thread, when trying to acquire * the write lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. * 如果当前线程在尝试获取写锁时阻塞,并且由于策略原因无法超过其他等待的线程, * 因此有资格这样做,则返回true。 */ abstractbooleanwriterShouldBlock();
finalbooleanreaderShouldBlock() { /* As a heuristic to avoid indefinite writer starvation, * block if the thread that momentarily appears to be head * of queue, if one exists, is a waiting writer. This is * only a probabilistic effect since a new reader will not * block if there is a waiting writer behind other enabled * readers that have not yet drained from the queue. * 作为一种避免无限writer饥饿的启发式方法, * 如果暂时出现队列头的线程(如果存在)是一个正在等待的writer,则阻塞。 * 这只是一种概率效应,因为如果在其他启用的reader后面有一个等待的writer, * 而这些reader还没有从队列中删除,则新reader不会阻塞。 */ return apparentlyFirstQueuedIsExclusive(); } finalbooleanapparentlyFirstQueuedIsExclusive() { Node h, s; return (h = head) != null && (s = h.next) != null && !s.isShared() && s.thread != null; }
finalbooleanreaderShouldBlock() { return hasQueuedPredecessors(); } publicfinalbooleanhasQueuedPredecessors() { // The correctness of this depends on head being initialized // before tail and on head.next being accurate if the current // thread is first in queue. Nodet= tail; // Read fields in reverse initialization order Nodeh= head; Node s; return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); }