pool.java
来自「用NETBEANS做的一个关于Java的小小的demo.大家赐教」· Java 代码 · 共 53 行
JAVA
53 行
/*
* 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 + =
减小字号Ctrl + -
显示快捷键?