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

📄 pool.java

📁 用NETBEANS做的一个关于Java的小小的demo.大家赐教
💻 JAVA
字号:
/*
 * Pool.java
 *
 * Created on 2007年9月14日, 上午11:42
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package semaphore;

import java.util.ArrayList;
import java.util.concurrent.Semaphore;

/**
 *
 * @author Administrator
 */
public class Pool {
    ArrayList<String> pool = null;
    Semaphore pass = null;
    public Pool(int size){
        //初始化资源池
        pool = new ArrayList<String>();
        for(int i=0; i<size; i++){
            pool.add("Resource "+i);
        }
        //Semaphore的大小和资源池的大小一致
        pass = new Semaphore(size);
    }
    public String get() throws InterruptedException{
        //获取通行证,只有得到通行证后才能得到资源
        pass.acquire();
        return getResource();
    }
    public void put(String resource){
        //归还通行证,并归还资源
        pass.release();
        releaseResource(resource);
    }
    private synchronized String getResource() {
        String result = pool.get(0);
        pool.remove(0);
        System.out.println("Give out "+result);
        return result;
    }
    private synchronized void releaseResource(String resource) {
        System.out.println("return "+resource);
        pool.add(resource);
    }
}

⌨️ 快捷键说明

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