多线程写锁优先访问java读写锁中的关键区域?

ztmd8pv5  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(317)

我需要writers线程优先于readers线程访问关键区域,我可以使用readwritelock接口来实现这一点吗?

iyfjxgzm

iyfjxgzm1#

而不是直接用 ReadWriteLock ,最简单的内置方法可能是 Semaphore ,这确实支持公平。创造公平 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);
    }
}

相关问题