【问题标题】:Java - How to modify semaphore implementation so it'll be fairJava - 如何修改信号量实现以使其公平
【发布时间】:2014-04-30 05:27:17
【问题描述】:

我正在使用 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();
        }
    }
}

【问题讨论】:

    标签: java concurrency semaphore reentrantlock


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 非常感谢!我的 acquire 和 acquireUninterruptibly 方法可以吗?它们几乎相同,所以我不确定我在这里是否做得很好......
    • 我会使用 Lock.awaitUninterruptibly() for acquireUninterruptibly()
    • Evgeniy,很好的答案。但是,您可能不知道该问题是家庭作业。通过发布您的答案,您无意中帮助学生作弊。
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2011-08-25
    相关资源
    最近更新 更多