resourcepool.java

来自「一步 教你学会java 完成一个完整的SWT系统 是本人学习java」· Java 代码 · 共 80 行

JAVA
80
字号
/** *   *  Concurrency utilities (JSR-166) example **/package semaphore;import java.net.*;import java.io.*;import java.util.concurrent.*;/** *  Use a Semaphore to control the usage of a pool of resources.  If a *  consumer requests a resource when all are being used the consumer  *  will block until aresource is returned and made available **/public class ResourcePool {  private int poolSize;  private Semaphore available;  private Integer[] resources;  private boolean[] used;  /**   *  Constructor   *   * @param poolSize Size of fixed pool of resources   **/  public ResourcePool(int poolSize) {    this.poolSize = poolSize;    /*  Create a pool of resources (for this example just a set of Integer     *  objects.  Create a new semaphore to control access to the resources     */    available = new Semaphore(poolSize);    used = new boolean[poolSize];    resources = new Integer[poolSize];    for (int i = 0; i < poolSize; i++)      resources[i] = new Integer(i);  }  /**   *  Get a resource.  If all are currently being used this will block   *  until one is returned to the pool.  This is a synchronised method    *  to make the code fully thread safe.   *   * @return The reource to use   **/  public synchronized Integer getResource() {    try {      available.acquire();    } catch (InterruptedException ie) {      // Ignore    }    for (int i = 0; i < poolSize; i++) {      if (used[i] == false) {        /*  If the method was not synchronised multiple threads could get to         *  this point and think that they both had the same resource         */        used[i] = true;        return resources[i];      }    }    return null;  }  /**   *  Return a resource to the pool   *   * @param resource The resource being returned to the pool   **/  public void putResource(Integer resource) {    /*  Note use of auto-unboxing  */    used[resource] = false;    available.release();  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?