2014-04-30 33 views
2

我正在Java中使用ReentrantLock实现SimpleSemaphore。Java - 如何修改信号量实现,以便公平

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

这是我的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(); 
     } 
    } 
} 

回答

3

试试这个

... 
    private ReentrantLock lock; 
    private Condition isZero; 

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

非常感谢您!我的获得和获得不间断的方法好吗?他们几乎是一样的,所以我不知道我是否在这里做得很好... – DanielY

+0

我会使用Lock.awaitUninterruptibly()获取不断变化的() –

+0

谢谢! :)... – DanielY