⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 resourcepool.java

📁 一步 教你学会java 完成一个完整的SWT系统 是本人学习java时按教程一步一步写下来的咯
💻 JAVA
字号:
/** *   *  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 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -