0

我需要编写器线程优先于读取器线程访问关键区域,我可以使用 ReadWriteLock 接口来执行此操作吗?

4

1 回答 1

1

虽然不是直接使用 a ReadWriteLock,但最简单的内置方法可能是 a Semaphore,它确实支持公平性。创建一个fair Semaphore,(有效)无限数量permis就足够了:

private static final Semaphore lock = new Semaphore(Integer.MAX_VALUE, true);

public void doReadLocked() throws InterruptedException {

    // 'Read' lock only acquires one permit, but since there are A LOT,
    // many of them can run at once.
    lock.acquire();
    try {
        // Do your stuff in here...
    } finally {

        // Make sure you release afterwards.
        lock.release();
    }
}

public void doWriteLocked() throws InterruptedException {

    // 'Write' lock demands ALL the permits.  Since fairness is set, this
    // will 'take priority' over other waiting 'read'ers waiting to acquire
    // permits.
    lock.acquire(Integer.MAX_VALUE);
    try {
        // Do your stuff in here...
    } finally {

        // Make sure you release afterwards.
        lock.release(Integer.MAX_VALUE);
    }
}
于 2021-04-24T22:50:54.820 回答