写锁优先访问java读写锁中的临界区?

问题描述

我需要写入线程优先于读取线程访问临界区,我可以使用 ReadWriteLock 接口来做到这一点吗?

解决方法

虽然不直接使用 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);
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...