Using semaphore to control number of threads

北慕城南 提交于 2020-01-25 18:39:05

问题


How can I make use of Semaphore class in order to control number of threads that have an access to an object?


回答1:


  • Initialize the Semaphore with the max number of alowed threds,
  • reduce the semaphore counter by one if a thread enters the restricted area
  • increse the semaphore counter by one if the thred leaves the restricted area



回答2:


One more good thing about using semaphore to control access to resouce is you can resize your semaphore at runtime. For eg you can have some use case where you want to allow more user to access resource based on some business logic and then reduce it again. Sample code for re sizable semaphore

public class ResizeableSemaphore extends Semaphore
{

    private static final long serialVersionUID = 1L;
    private int permit;
    public ResizeableSemaphore(int permit) {
        super(permit);
        this.permit=permit;
    }       

    public synchronized void resizeIfRequired(int newPermit)
    {
        int delta = newPermit - permit;
        if(delta==0) return;
        if(delta > permit) this.release(delta); // this will increase capacity
        if(delta < 0) this.reducePermits(Math.abs(delta));
        this.permit=newPermit;
    }   
}



回答3:


This is a great example of how Semaphore can be used to limit concurrent access to an object:

http://technicalmumbojumbo.wordpress.com/2010/02/21/java-util-concurrent-java-5-semaphore/

The key points being:

  • When you construct the Semaphore, you can declare the max concurrency (i.e., number of threads allowed to access concurrently)
  • You require each thread to attempt to acquire() the Semaphore; let the Semaphore keep track of concurrent access



回答4:


Just use:

java.util.concurrent.Semaphore

there's an extensive example on how to use it in the javadoc:

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Semaphore.html




回答5:


Perhaps you could read the answer to this question, and have a look at this example



来源:https://stackoverflow.com/questions/5270433/using-semaphore-to-control-number-of-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!