Java - 如何修改信号量实现以使其公平

标签 java concurrency semaphore reentrantlock

我正在 Java 中使用 ReentrantLock 实现 SimpleSemaphore。

现在,我想为它添加一个公平标志,使其表现为公平\不公平信号量,如其构造函数中所定义。

这是我的 SimpleSemaphore 代码,我很高兴获得一些有关如何开始实现公平性的提示。谢谢。

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

/**
 * @class SimpleSemaphore
 *
 * @brief This class provides a simple counting semaphore
 *        implementation using Java a ReentrantLock and a
 *        ConditionObject.  It must implement both "Fair" and
 *        "NonFair" semaphore semantics, just liked Java Semaphores. 
 */
public class SimpleSemaphore {
    private int mPermits;
    private ReentrantLock lock = new ReentrantLock();
    private Condition isZero = lock.newCondition();

    /**
     * Constructor initialize the data members.  
     */
    public SimpleSemaphore (int permits,
                            boolean fair)
    { 
        mPermits = permits;
    }

    /**
     * Acquire one permit from the semaphore in a manner that can
     * be interrupted.
     */
    public void acquire() throws InterruptedException {
        lock.lock();
        while (mPermits == 0)
            isZero.await();
        mPermits--;
        lock.unlock();
    }

    /**
     * Acquire one permit from the semaphore in a manner that
     * cannot be interrupted.
     */
    public void acquireUninterruptibly() {
        lock.lock();
        while (mPermits == 0)
            try {
                isZero.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        mPermits--;
        lock.unlock();
    }

    /**
     * Return one permit to the semaphore.
     */
    void release() {
        lock.lock();
        try {
            mPermits++;
            isZero.signal();
        } finally {
            lock.unlock();
        }
    }
}

最佳答案

试试这个

...
    private ReentrantLock lock;
    private Condition isZero;

    public SimpleSemaphore (int permits, boolean fair) { 
        mPermits = permits;
        lock = new ReentrantLock(fair);
        isZero = lock.newCondition();
    }

关于Java - 如何修改信号量实现以使其公平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23380303/

相关文章:

java - 从随机持续时间获取平均值

javascript - Javascript/jQuery ajax调用同步的常用做法

ios - Playground——DispatchQueue和DispatchSemaphore的关系

java - 如何将 Google Plus One 按钮添加到 Android lwp 的设置中?

java - 分析 Java 中的线程行为

java - SFTP 连接抛出奇怪的 FileTransferException,暴露了 SFTP 密码

c++ - 寻找设计建议 - 统计记者

posix - 名称和未命名信号量

java - 哪个Jdk版本支持windows xp

java - 使用 `Error: Could not find or load main class` 运行 jar